Solve - SyntaxError: invalid syntax in if statement (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Check out my new book

Solve - SyntaxError: invalid syntax in if statement (Python) #

The Python "SyntaxError: invalid syntax" is often caused when we use a single equals sign instead of double equals in an if statement. To solve the error, use double equals == if comparing values and make sure the line of the if statement ends with a colon.

syntaxerror invalid syntax if statement

Here is an example of how the error occurs.

main.py
name = 'Alice' # ⛔️ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? if name = 'Alice': print('success')

The error is caused because we used a single equals sign instead of double equals.

If comparing values, make sure to use double equals.

main.py
name = 'Alice' if name == 'Alice': # 👇️ this runs print('success')

Make sure the line of the if statement ends with a colon :.

Another common cause of the error is forgetting to indent your code properly.

The code in the if statement should be consistently indented.

If the error is not resolved, look at the code that's right above the if statement and make sure you haven't forgotten to close a parenthesis ), a square bracket ] or a curly brace }.

If you have an if/else statement, make sure the else statement also ends with a colon and its code is indented consistently.

main.py
name = 'Alice' if name == 'Alice': # 👇️ this runs print('success') else: print('failure')

If you have an if or else statement that you haven't yet implemented, use a pass statement.

main.py
name = 'Alice' if name == 'Alice': print('success') else: pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.