user2958053
user2958053

Reputation: 1

Invalid Syntax on Python if statement

I have recently started using Python and I was typing out a simple code when I got an Invalid syntax error does anyone understand where I went wrong?

Swansea= 2

Liverpool= 2

If Swansea < Liverpool:
    print("Swansea beat Liverpool")

If Swansea > Liverpool:
    print("Liverpool beat Swansea")

If Swansea = Liverpool:
    print("Swansea and Liverpool drew")

The word "Swansea" becomes highlighted in red

Upvotes: -1

Views: 6885

Answers (3)

user2555451
user2555451

Reputation:

You have two problems:

  1. You need to use == for comparison tests, not = (which is for variable assignment).
  2. if needs to be lowercase. Remember that Python is case-sensitive.

However, you should be using elif and else here since no two of those expressions could ever be True at the same time:

Swansea=2

Liverpool=2

if Swansea < Liverpool:
    print("Swansea beat Liverpool")

elif Swansea > Liverpool:
    print("Liverpool beat Swansea")

else:
    print("Swansea and Liverpool drew")

Though using three separate if's won't generate an error, using elif and else is much better for two reasons:

  1. Code clarity: It is a lot easier to see that only one of the expressions will ever be True.
  2. Code efficiency: Evaluation will stop as soon as an expression is True. Your current code however will always evaluate all three expressions, even if the first or the second is True.

Upvotes: 4

jramirez
jramirez

Reputation: 8685

You are probably getting the syntax error because of all the If they need to be lower case if. Also the equality operator is == not =

if Swansea == Liverpool: 
     print("Swansea and Liverpool drew")

Upvotes: 3

Paulo Bu
Paulo Bu

Reputation: 29804

Python is case sensitive so probably If is raising invalid syntax. Should be if.

Upvotes: 1

Related Questions