Python - How To Fix Keywords Cannot Be Expression Error in Python

ID : 498

viewed : 98

Tags : PythonPython KeywordsPython Error

vote vote

98

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'} 

  • Related HOW TO?