SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
What it means
You used a single = where Python expected a condition. One = stores a value in a variable. Two, ==, asks whether two values are equal, which is what an if, elif or while needs.
1. Using `=` to compare in an `if`
This raises the error
Broken
password = "python123"
if password = "python123":
print("Access granted")
Output
Traceback (most recent call last):
File "<exec>", line 2
if password = "python123":
^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?The fix
Fixed
password = "python123"
if password == "python123":
print("Access granted")
Output
Access granted
== compares the two sides and gives True or False, which is what an if needs to decide.
2. One `=` in an `elif` after a correct `if`
This raises the error
Broken
day = "Sat"
if day == "Mon":
print("Back to work")
elif day = "Sat":
print("Weekend!")
Output
Traceback (most recent call last):
File "<exec>", line 4
elif day = "Sat":
^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?The fix
Fixed
day = "Sat"
if day == "Mon":
print("Back to work")
elif day == "Sat":
print("Weekend!")
Output
Weekend!
Every condition needs its own ==. A program can be right in one branch and wrong in the next.
3. Trying to store a value inside the condition
This raises the error
Broken
words = ["hi", "hello", "hey"]
if n = len(words):
print(n, "words")
Output
Traceback (most recent call last):
File "<exec>", line 2
if n = len(words):
^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?The fix
Fixed
words = ["hi", "hello", "hey"]
if (n := len(words)) > 2:
print(n, "words")
Output
3 words
To store a value and test it in one go, Python uses the walrus operator :=. A plain n = len(words) on the line before the if is just as good and easier to read.
When you see this error, check
- In
if,elifandwhileconditions, compare with==. - Use
!=for not equal, and<=or>=for less or greater than or equal. - Keep a single
=for lines that store a value, likename = "Ada". - Inside a list comprehension,
[n for n in nums if n % 2 = 0]gives a plaininvalid syntax, but the fix is the same==.
Related errors
All Python errors · How to read a traceback · Step through your code