Python SyntaxError: invalid syntax
SyntaxError: invalid syntax
This means Python met a line that does not follow its syntax while reading your code. It is caught before anything runs, so not a single line of the program is executed. The error message shows the line number, the code on that line, and a ^ mark pointing at the spot with the problem. Look at the ^ spot and just before it.
Cause 1. You used a single = to ask if two things are equal
= stores a value, and the sign that asks whether two things are equal is ==. Using = inside an if is a syntax error. In this case the hint Maybe you meant '==' or ':=' instead of '='? is added at the end.
Wrong code
x = 5if x = 5: print("five") File "main.py", line 2
if x = 5:
^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?Fixed code
Change it to ==.
Cause 2. You used syntax from another language
Python has no i++ or i--. If you learned C or JavaScript first, they are a habit and slip in often. Grouping with braces, as in if x > 2 {, is the same error.
Wrong code
i = 0while i < 3: print(i) i++ File "main.py", line 4
i++
^
SyntaxError: invalid syntaxFixed code
To add 1, write i += 1. Blocks are marked with a colon and indentation instead of braces.
Cause 3. The variable name has a space in it
A name must be one word. my score is read as two names side by side, which is not valid syntax.
Wrong code
my score = 90print(my score) File "main.py", line 1
my score = 90
^^^^^
SyntaxError: invalid syntaxFixed code
Join the words with an underscore _.
Words that Python already uses, such as class, for, if and in, cannot be variable names either. class = 3 is invalid syntax. A name that starts with a digit (2nd) is not allowed either, but then the message is invalid decimal literal.
Cause 4. The symbols are in the wrong order
"Greater than or equal" is >=, "less than or equal" is <=, and "not equal" is !=. The = always comes last. Writing => or =< is a syntax error.
Wrong code
x = 5if x => 3: print("ok") File "main.py", line 2
if x => 3:
^
SyntaxError: invalid syntaxFixed code
Change it to >=.
You also get invalid syntax when a value is missing after a symbol, as in 3 +, or when symbols are doubled up, as in x +* 2.
What to check when you see this error
- Look at the number after
lineand the spot the^mark points to in the error message. The problem is at that spot or just before it. - If the error message is not
invalid syntaxbut something more detailed, that message is the answer.expected ':'means the colon is missing at the end of anif,for,while,deforelseline (you also get it if you writeelse if. In Python it iselif). '(' was never closedmeans you opened a parenthesis and did not close it, andunterminated string literalmeans you did not close a quote.Missing parentheses in call to 'print'means you wrote it without parentheses, likeprint "hi". Change it toprint("hi").- If
Perhaps you forgot a comma?is added, check whether a comma is missing between values.print(a b)is one such case.