How Do You Troubleshoot “SyntaxError: invalid syntax” in Python?

Problem scenario
You are running a Python script. You keep getting "SyntaxError: invalid syntax" and a line number. You can find nothing wrong with the syntax on the specified line number. What do you do?

Possible solution #1
Look at the line with code, as opposed to blank line(s), above it. Is there a missing quote, brace, bracket or parentheses?

Possible solution #2
Are you trying to use an "if" statement on one line? Make sure you have an "else" statement. Without an "else" clause, you can get "SyntaxError: invalid syntax". Here are four lines of code that are minimally correctly written:

f = 5
a = "unique"
x = f
print("scissors" if a == "unique" else "rocks")

# You could try to eliminate the 'else "rocks"' portion and run the program to see the error.

Leave a comment

Your email address will not be published. Required fields are marked *