How to Fix Keywords Cannot Be Expression Error in Python

Manav Narula Feb 02, 2024
How to Fix Keywords Cannot Be Expression Error in Python

Keywords are reserved words with a specific purpose, and keyword arguments in Python are values passed to a function identified using the parameter’s name.

We will get to know how to fix the keyword can't be an expression in this article. It falls into SyntaxError in Python. A SyntaxError is raised when the basic syntax of Python is not followed.

This error is encountered in the following example.

def display(a):
    print(a)


display(a.first="Hello")

Output:

SyntaxError: keyword can't be an expression

In the above example, a is the keyword, and Hello is the argument value. We encounter the error because the keyword is an expression and has a dot (.first).

We can correct this by ensuring that the keyword is not in the form of an expression.

def display(a):
    print(a)


display(a="Hello")

Output:

Hello

We usually get this error by performing simple operations related to passing values to a function. Take another example of this error while creating a dictionary using the dict() function.

See the code below.

a = dict("name"="delft", "lname"="stack")

Output:

SyntaxError: keyword can't be an expression

While using the dict() constructor, the keys are passed as arguments, and they are interpreted as an expression by putting them in quotes. We can avoid this by removing the quotes in the keys.

For example:

a = dict(name="delft", lname="stack")
print(a)

Output:

{'name': 'delft', 'lname': 'stack'}
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