The Python "SyntaxError: invalid syntax" occurs when there is invalid syntax in the code. This means the code is not "proper" Python and is missing something, has extra characters, or is an invalid usage of a statement (such as if-else, for loops, try-except). This can be fixed by debugging the code to figure out where the error is.
Here are some examples that cause a SyntaxError
.
# ⛔️ SyntaxError: invalid syntax
# missing quotes around `Hello`
print(Hello)
# ✅ this runs
print("Hello")
# -----------------------
# ⛔️ SyntaxError: invalid syntax
# for loop statement requires code inside the loop
for item in box:
# ✅ this runs
for item in box:
print(item)
# -----------------------
# ⛔️ SyntaxError: invalid syntax
# there is a missing comma
# each element of a dictionary needs to be separated by a comma
trees = {
"maple": 5,
"oak": 14
"redwood": 9
}
# ✅ this runs
trees = {
"maple": 5,
"oak": 14,
"linden": 9
}
When a SyntaxError
is reported on a line that appears correct, try commenting out that line. If the error moves to the next line, then:
The second one is more likely, especially if commenting out another line causes the error to move again.
Here is an example.
# this is missing a closing integer and parentheses
number_of_squares = (5 +
# ⛔️ SyntaxError: invalid syntax will occur on this line
number_of_circles = 8
# -----------------------
# ✅ this runs
number_of_squares = (5 + 8)
number_of_circles = 8
The error is produced on the second line, even though the problem is caused by the first line.
The Python "SyntaxError: invalid syntax" occurs when there is invalid syntax in the code. This means the code is not "proper" Python and is missing something, has extra characters, or is an invalid usage of a statement (such as if-else, for loops, try/except). This can be fixed by debugging the code to figure out where the error is.
Related tutorials curated for you
TypeError: a bytes-like object is required, not 'str'
ValueError: setting an array element with a sequence
ModuleNotFoundError: No module named 'pip' in Python
ModuleNotFoundError: No module named 'matplotlib' in Python
Flatten a list in Python
Delete Conda environment
How to fix: Unindent does not match any outer indentation level in Python
IndexError: list index out of range
ModuleNotFoundError: No module named 'cv2' in Python
ModuleNotFoundError: No module named 'pandas' in Python
TypeError: only integer scalar arrays can be converted to a scalar index
How to fix: pandas data cast to numpy dtype of object. Check input data with np.asarray(data)