Syntax error: what it is and how to fix SyntaxError: invalid syntax in Python

A syntax error is code that breaks the grammar rules of its programming language, so the parser cannot read it and the program never starts. In Python it appears as SyntaxError: invalid syntax or a more specific message such as expected ':'. To fix it, open the file at the reported line, look at the caret (^) and the line just before it, and correct the missing colon, bracket, quote, comma or misused keyword.
This guide explains what the error message tells you, lists the most common Python syntax error messages with their fixes, and shows how to check a file for syntax errors without running it.

What is a syntax error?
A syntax error is a mistake in the structure of code, not in its logic. Every programming language has a grammar: which characters open and close blocks, where separators go, which words are reserved. When code breaks that grammar, the parser rejects it before a single line runs. The Python tutorial describes syntax errors as parsing errors, and JavaScript behaves the same way: MDN defines a JavaScript SyntaxError as an error thrown when the engine meets tokens or token order that does not conform to the language's syntax.
That timing is what separates syntax errors from other errors:
- Syntax error: the code cannot be parsed, so nothing executes. A single typo anywhere in a Python file stops the whole file.
- Runtime error (exception): the code is valid, but something fails while it runs, for example
NameErrorfor an unknown name orZeroDivisionError. - Logic error: the code runs without any error but produces the wrong result.
A common misconception, repeated in many guides, is that a misspelled name causes a syntax error. It does not: prnt("hi") is valid Python grammar and fails at runtime with NameError: name 'prnt' is not defined. Did you mean: 'print'?
How to read a Python SyntaxError message
A Python SyntaxError message has four parts: the file name, the line number, a copy of the offending line with carets (^) under the problem, and the message text. Python raises it when parsing a script, an imported module, or code passed to compile(), exec() or eval(), according to the built-in exceptions reference.
The tutorial's own example shows why the caret needs interpretation:
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^^^^^
SyntaxError: invalid syntax
The carets point at print, but the fix is the missing colon after True. The caret marks where the parser gave up, which is often one token, or one line, after the real mistake. Two rules follow from that:
- Read the message text first. Since Python 3.10 it often names the problem directly.
- If the reported line looks correct, check the line above it, especially for an unclosed bracket or quote.
Python 3.10 also added end_lineno and end_offset to SyntaxError, which is why modern versions underline a whole range with several carets instead of a single one.
Common Python syntax error messages and how to fix them
Most Python syntax errors come from a handful of causes, and current Python versions name them in the message. The messages below are the exact output of Python 3.13 for each broken snippet; the Python 3.10 release notes document when these specific messages replaced the generic "invalid syntax".
| Message | Typical cause | Fix |
|---|---|---|
expected ':' |
if x == 5 with no colon (also def, for, while, class) |
Add the colon at the end of the line: if x == 5: |
'(' was never closed |
print("hello" with no closing parenthesis |
Add the closing bracket; the caret points at the opening one |
unterminated string literal |
print("This is a string) |
Close the quote with the same quote type: print("This is a string") |
invalid syntax. Perhaps you forgot a comma? |
items = [1, 2 3] |
Add the comma between list, tuple, dict or argument items |
invalid syntax. Maybe you meant '==' or ':=' instead of '='? |
if x = 5: |
Use == to compare values |
Missing parentheses in call to 'print'. Did you mean print(...)? |
Python 2 code such as print "hello" |
Write print("hello"); port the rest of the Python 2 code too |
invalid character '“' (U+201C) |
Curly quotes pasted from a word processor, chat or web page | Retype the quotes as straight " or ' |
invalid syntax |
A reserved keyword used as a name, for example if = 5 or class = "a" |
Rename the variable, for example class_name |
If the message is still the generic invalid syntax on an older interpreter, upgrading Python often turns it into one of the specific messages above.
Indentation errors: IndentationError and TabError
IndentationError and TabError are Python syntax errors too: the exceptions reference lists IndentationError as a subclass of SyntaxError and TabError as a subclass of IndentationError. Python uses indentation to define blocks, so whitespace mistakes break the grammar just like a missing bracket. The three messages you will see most often:
IndentationError: expected an indented block after function definition on line 1: the body of adef,ifor loop is not indented. Indent it, or addpassas a placeholder.IndentationError: unexpected indent: a line is indented where no block was opened. Align it with the surrounding code.TabError: inconsistent use of tabs and spaces in indentation: a block mixes tab characters and spaces. Convert the file to spaces only (PEP 8 recommends four per level).
Tabs and spaces look identical in most editors, which makes TabError hard to see. Turn on visible whitespace in your editor, or use its "convert indentation to spaces" command on the whole file. A coding font such as Microsoft's Cascadia Code also makes look-alike characters easier to tell apart.
Reserved keywords that cause invalid syntax
Python has 35 hard keywords that can never be used as variable, function or class names, and using one usually produces SyntaxError: invalid syntax (assigning to True, False or None gives cannot assign to True and similar). The lexical analysis reference lists them:
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
The keywords that trip people up most are class, from, import, global, lambda and async, because they are also natural variable names in data and web code. The usual fix is a trailing underscore (class_, from_) or a more descriptive name (from_date).
Soft keywords are different: match, case, _, type and, since Python 3.15, lazy are reserved only inside specific statements. match = 5 is still valid code, so an older script that uses these names keeps working. To check any word, run import keyword and then keyword.iskeyword("word") in the interpreter.

How to find syntax errors before you run the code
The fastest way to find Python syntax errors is to let a tool parse the file for you. Three options cover most setups:
- Compile without running:
python -m py_compile script.pyparses the file and prints the SyntaxError if there is one. The py_compile documentation notes that the exit status is nonzero when a file cannot be compiled, which makes it usable in scripts and pre-commit hooks. - Use an editor with a Python language server: Visual Studio Code with the Python extension, PyCharm and similar editors underline syntax errors as you type.
- Compare with the last working version: if a file worked yesterday, a diff tool such as Meld shows exactly which lines changed.
When a whole project fails, search the code base for the reported construct (for example every print ") with a multi-file search such as Notepad++ Find in Files.
Copying code from web pages, PDFs or chat apps is a frequent source of hidden problems: curly quotes, non-breaking spaces and mixed tabs. If a pasted snippet fails with an error on a line that looks fine, retype that line by hand.
FAQ
Can a syntax error be caught with try and except?
Not in the same file: the file fails to parse before the try block exists. You can only catch a SyntaxError raised by code parsed later, for example through import, exec() or compile().
Why does the error point to the wrong line?
The caret shows where the parser stopped, not where the mistake was made. An unclosed bracket or quote on one line is often reported on a following line, so always check the lines above the one reported.
Why does code that works for someone else give me invalid syntax?
The two of you are probably running different Python versions. Code written for Python 2, or code using newer syntax such as the match statement (Python 3.10) on an older interpreter, raises SyntaxError; run python --version to check.
Related: Compare files and folders with Meld, Find text in all files of a folder with Notepad++, Cascadia Code, Microsoft's open source coding font
It would have helped if the article was using clear code block formatting, this WordPress installation on gHacks does support such things.
For example:
if x == 5:print("x is equal to 5")
However, I cannot yet tell how the above code will render, or whether it will display on two lines with the correct indentation (or collapse the whitespace or print the NCR) because there is no ‘post preview’ for visitors. :-/
Python (programming language) uses indentation to indicate a block of code (the second line in the code sample should have had indentation). Thus, neither presented code example was correct.
NB: Perhaps taking more time proofreading after posting the article submission, and understanding at least tiny bit about the topic in the first place might have helped.
This article was written by AI, not by a person… fyi.
Is this serious? Why??
Syntax error means you’re stupid, most IDEs will just tell you which line the error is at.
The missing punctuation example is so retarded because both versions have the semi-colon, what the heck! Also both examples will fail due to improper indentation….
Chat GPT has a long way to go before it’s any good, clearly.
Your first example has the same code listed before and after the “fix”.
”
For example, the following code will raise a SyntaxError: invalid syntax error because it is missing a colon at the end of the ”if ”statement:
if x == 5:
print(“x is equal to 5”)
To fix this error, simply add a colon to the end of the if statement:
if x == 5:
print(“x is equal to 5”)
“