Borislav Hadzhiev
Mon Apr 25 2022·2 min read
Photo by Tiko Giorgadze
The Python "SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?" occurs when we try to assign to a literal (e.g. a string or a number). To solve the error, specify the variable name on the left and the value on the right-hand side of the assignment.
Here are 2 examples of how the error occurs.
# ⛔️ SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? 1 = 'abc' # ⛔️ SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? 'name' = 'Alice'
1
and the string name
.When declaring a variable make sure the variable name is on the left-hand side
and the value is on the right-hand side of the assignment (=
).
my_num = 1 name = 'Alice'
Notice that variable names should be wrapped in quotes as that is a string literal.
The string "name"
is always going to be equal to the string "name"
, and the
number 100
is always going to be equal to the number 100
, so we cannot
assign a value to a literal.
You can think of a variable as a container that stores a specific value.
employee = {'name': 'Alice', 'age': 30}
Variable names should not be wrapped in quotes.
If you got the error while declaring multiple variables on the same line, use the following syntax.
a, b = 1, 2 print(a) # 👉️ 1 print(b) # 👉️ 2
The variable names are still on the left, and the values are on the right-hand side.
If you meant to perform an equality comparison, use double equals.
my_num = 100 if 100 == my_num: # 👇️ this runs print('success') else: print('failure')
We use double equals ==
for comparison and single equals =
for assignment.
The name of a variable must start with a letter or an underscore.
A variable name can contain alpha-numeric characters (a-z
, A-Z
, 0-9
) and
underscores _
.
my_num = 100 my_color = 'green'
Note that variable names cannot start with numbers or be wrapped in quotes.
Variable names in Python are case-sensitive.
my_color = 'green' MY_COLOR = 'red' print(my_color) # 👉️ 'green' print(MY_COLOR) # 👉️ 'red'
The 2 variables in the example are completely different and are stored in different locations in memory.