Programmers frequently encounter an error known as syntaxerror keyword can t be an expression.
This particular error message can be quite perplexing, especially for individuals who are new to programming or are unfamiliar with the language being utilized.
In this article, we will discuss this error and explore solutions to assist you in troubleshooting it.
So, let’s delve into how to fix syntaxerror: keyword can’t be an expression error message.
What is “syntaxerror: keyword can’t be an expression”?
The error message syntaxerror: keyword can’t be an expression occurs when you are using a non-valid keyword argument name.
Keyword arguments prove beneficial when passing values to functions. However, if you attempt to utilize invalid keyword arguments, the Python interpreter will generate a SyntaxError.
For example:
Sample = dict('website'='Itsourcecode','offers'='Free sourcecode and tutorials','visitors'=3000000)
print(Sample)Output:
File "C:\Users\pies-pc2\PycharmProjects\pythonProject\main.py", line 1
Sample = dict('website'='Itsourcecode','offers'='Free sourcecode and tutorials','visitors'=3000000)
^^^^^^^^^^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?Also, if you try to use a dot in a keyword argument name like sum.up=False, it will raise a SyntaxError because it is not a valid argument name.
You can only use alphanumerics and underscores in argument name.
If you are confused about syntaxerror: expression cannot contain assignment and syntaxerror keyword can t be an expression, if they the same or not?
Both errors are related to syntax and indicate a violation of language rules but they have different causes.
The syntaxerror: expression cannot contain assignment triggered by an assignment within an expression.
To fix this error, specify the variable name on the left and the expression on the right-hand side.
Meanwhile, syntaxerror: keyword can’t be an expression occurs when a keyword is used as an expression or variable.
Why does the “keyword can’t be an expression” SyntaxError occur?
The syntax error keyword can’t be an expression occurs due to the specific rules and limitations set by the programming language.
Programming languages have reserved keywords that serve predefined purposes within the language’s syntax. These keywords are not meant to be used as variables or expressions.
When a keyword is mistakenly used as an expression, the interpreter or compiler flags it as a syntax error to ensure the code’s correctness and adherence to the language’s rules.
How to fix “syntaxerror keyword can t be an expression”?
To fix the syntaxerror: keyword can’t be an expression error, ensure that you are using valid keyword argument names. Keyword arguments must be valid identifiers, which means you can only use alphanumerics and underscores in argument names.
Solution 1: Remove non-valid keyword
Incorrect code:
Sample = dict('website'='Itsourcecode','offers'='Free sourcecode and tutorials','visitors'=3000000)
print(Sample)As you can see, our example code is incorrect. So in order to fix this error we to remove the non-valid keyword which you can see in the corrected code 1 below.
Corrected code 1:
✅ Sample = dict(website = 'Itsourcecode',offers = 'Free sourcecode and tutorials', visitors = 3000000)
print(Sample)Corrected code 2:
✅ Sample = {'website': 'Itsourcecode', 'offers': 'Free sourcecode and tutorials', 'visitors': 3000000}
print(Sample)
In this solution, we are creating a dictionary using the curly braces {} syntax and specifying the key-value pairs using the key: value syntax. This is a valid way to create a dictionary and will not raise any errors.
The output is still the same.
Output:
{'website': 'Itsourcecode', 'offers': 'Free sourcecode and tutorials', 'visitors': 3000000}
Solution 2: Use valid keyword argument names:
In this example, we are calling the sample_function with valid keyword argument names x and y.
def sample_function(x, y):
return x + y
result = sample_function(x=10, y=20)
print(result)Output:
30Conclusion
In conclusion, the error message syntaxerror: keyword can’t be an expression occurs when you are using a non-valid keyword argument name.
To fix this syntaxerror, ensure that you are using valid keyword argument names. Keyword arguments must be valid identifiers, which means you can only use alphanumerics and underscores in argument names.
This article already discussed what this error is all about and multiple ways to resolve this error.
By executing the solutions above, you can master this SyntaxError with the help of this guide.
You could also check out other SyntaxError articles that may help you in the future if you encounter them.
- Syntaxerror: invalid non-printable character u+00a0
- Syntaxerror: await outside function
- Pip install syntaxerror: invalid syntax
We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊
Why keyword SyntaxError happens
Python has 35+ reserved keywords. Using them as variable names, function names, or class names raises SyntaxError.
Common triggers
- Using class as variable.
class = "MyClass"— class is reserved. - Using return outside function. Raises SyntaxError.
- Using None/True/False as identifier. Since Python 3, they are true keywords.
- Soft keywords used incorrectly. match/case (Python 3.10+) are soft keywords — can be identifiers but not in match statements.
- Non-ASCII identifiers. Allowed in Python 3, but Greek letters and other exotic chars can look like reserved words.
Diagnostic pattern
# BAD — class as variable class = MyModel # SyntaxError # GOOD — use alternative name model = MyModel klass = MyModel # convention # BAD — return outside function return 42 # SyntaxError # GOOD — wrap in a function or use sys.exit at top level import sys sys.exit(0) # Complete Python keyword list (Python 3.12): # False, None, True, and, as, assert, async, await, break, class, # continue, def, del, elif, else, except, finally, for, from, global, # if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, # try, while, with, yield
Best practices
- Avoid names that shadow builtins. Not a SyntaxError but confusing: list, dict, str.
- Use snake_case for variables. Clear separation from CamelCase class names.
- Trailing underscore is Python convention for shadowed name:
class_ = MyModel. - Configure linter. Ruff catches keyword shadowing warnings.
Official documentation
Frequently Asked Questions
What is Python SyntaxError and what causes it?
SyntaxError is raised when Python’s parser can’t understand your code. Common causes: missing colon (def foo() instead of def foo():), unmatched parentheses or brackets, incorrect indentation, mixing tabs and spaces, missing comma in a list, or using a Python 3 feature in a Python 2 interpreter (or vice versa). The error points to a line, but the actual issue is often on the line BEFORE.
How do I fix ‘unexpected EOF while parsing’?
Python ran out of code while expecting more, usually unclosed parenthesis, bracket, brace, or quote. Scroll up from the error line and count opening vs closing pairs. Use an IDE with bracket matching (VS Code, PyCharm) to highlight pairs. Common gotcha: a triple-quoted string that’s missing its closing triple-quote.
Why does my syntax error point to a line that looks correct?
The actual error is often on the line BEFORE the one Python reports. Python reads code until something doesn’t parse, then reports the position where it gave up, not where the user’s mistake started. Check the line above the reported error for missing colons, commas, or closing brackets.
Why does ‘print x’ raise SyntaxError in Python 3?
Python 3 made print a function, so print(x) is required. The bare ‘print x’ syntax was Python 2 only. If you’re following an old tutorial, check whether it targets Python 2 (released 2008) or Python 3 (your current interpreter). Update all print statements to print(…) function calls.
Where can I find more SyntaxError fixes?
Browse the SyntaxError reference hub for 48+ specific fixes (Python and JavaScript). For Python fundamentals see the Python Tutorial hub. For JavaScript syntax errors see the JavaScript Tutorial hub.
