SyntaxPython Error

SyntaxError

SyntaxError: invalid syntax

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print "Hello, World!"  # Python 2 syntax
SyntaxError: invalid syntax

What causes this error

The code violates Python's grammar rules in a way that does not fit a more specific error category. The actual problem may be on the line indicated or the line above it.

How to fix it

Check the indicated line and the line above for missing colons, brackets, or quotes. Look for Python 2 syntax if migrating. Ensure reserved keywords are not used as variable names. Use an editor with syntax checking.

Code that causes this error

Broken
print "Hello, World!"  # Python 2 syntax

Fixed code

Fixed
print("Hello, World!")  # Python 3 syntax

About SyntaxError

The 'invalid syntax' message is the most generic form of SyntaxError — Python could not parse the code but does not have a more specific message to give. This catch-all message appears for a wide variety of parsing failures. In newer Python versions (3.10+), many cases that previously showed 'invalid syntax' now have more descriptive messages.

The remaining cases where you see this generic message include using Python 2 syntax in Python 3 (like `print "hello"`), placing expressions where statements are expected, using reserved keywords as variable names, and various structural problems that do not fit into specific SyntaxError categories. The caret (^) in the traceback points to where the parser got confused, but the actual error may be on the previous line — for example, a missing closing parenthesis on line 5 might cause 'invalid syntax' on line 6.

Common scenarios

1

Writing code with missing colons, parentheses, or brackets

2

Mixing Python 2 and Python 3 syntax when upgrading a codebase

3

Copy-pasting code from the web with formatting issues or invisible characters

4

Using reserved keywords as variable or function names

Related errors