SyntaxError: cannot assign to literal here (Python)

avatar

Borislav Hadzhiev

Mon Apr 25 20222 min read

SyntaxError: cannot assign to literal here (Python) #

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.

syntaxerror cannot assign to literal here

Here are 2 examples of how the error occurs.

main.py
# ⛔️ 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'
The error is caused because we are trying to assign a value to 2 literals - the integer 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 (=).

main.py
my_num = 1 name = 'Alice'

Notice that variable names should be wrapped in quotes as that is a string literal.

The left-hand side of the assignment cannot be a literal like a string or a number.

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.

main.py
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.

main.py
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.

main.py
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 _.

main.py
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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.