Python SyntaxError: Can't Assign to Literal Error in Python

Python SyntaxError: Can't Assign to Literal Error in Python

  1. the SyntaxError: can't assign to literal in Python
  2. Fix the SyntaxError: can't assign to literal in Python

This short tutorial will discuss the SyntaxError: Can't assign to literal error in Python.

the SyntaxError: can't assign to literal in Python

This syntax error is encountered when we try to assign some value to a literal. It is a SyntaxError because it violates the syntax of Python.

Code Example:

5 = "Hello"
"Hello" = 5

Output:

SyntaxError: can't assign to literal

Both lines in the above code will generate this error because both are literal values (an integer and a string), not a variable.

We can assign values only to variables. Variables are assigned using the = operator in Python.

We follow some provided conventions while naming the variable, and the variable name should begin with a letter or the underscore character. It can follow any alpha-numeric characters.

Fix the SyntaxError: can't assign to literal in Python

The way to fix this is to follow the proper naming convention and create a variable that can store the data.

Code Example:

a5 = "Hello"
Hello = 5
print(a5,Hello)

Output:

Hello 5

In the above example, we create proper variables, assign them the required values, and print them. Note that the variable names are case-sensitive in Python.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10