Python SyntaxError: what "invalid syntax" means and how to fix it

Try an example:

Paste the code that fails and press Explain. You get the line, the cause in plain words and an example of the fix. The code is checked in your browser and is not run.

How to read a SyntaxError

Python reads the whole file before it runs anything. If it cannot read the code, it stops and reports a SyntaxError. At that point no line of the program has run.

The report has three parts: the file and the line number, the line itself with a marker under the place where Python stopped, and the name of the error with a short message.

  File "main.py", line 2
    if x > 3
            ^
SyntaxError: expected ':'
  • Python reports only the first syntax error. Fix it and check again to see the next one.
  • The marker shows where Python stopped reading. The mistake is at that place or just before it.
  • Python 3.9 and older often report an open bracket one line too late: the error points at the next line. If the marked line looks right, look at the line above.

What is a syntax error in Python

A syntax error means that the code breaks the grammar of the language, so Python cannot split it into valid statements. It is different from an error that happens while a program runs, such as NameError or TypeError: those appear only when the faulty line is executed. With a syntax error nothing runs at all. IndentationError and TabError are kinds of SyntaxError.

Invalid syntax: meaning and causes

"invalid syntax" is the message Python uses when it cannot name the problem. It only says where it stopped reading. Newer versions of Python name many causes directly. Python 3.9 and older use the plain "invalid syntax" for most of them. Where an older version words the message differently, the card below shows that wording.

How to fix a syntax error in Python

  1. Go to the line in the message. Look at the place under the marker, then just before it.
  2. Look for the usual slips: a missing colon, a bracket or quote that is never closed, a misspelled keyword, a missing comma.
  3. If that line looks right, check the line above for an open bracket or quote.
  4. Fix it and check again. Python reports one syntax error at a time.

Paste your code above and press Explain to see the cause for your line. When an invalid syntax Python message names no cause, its card in the reference below lists what to check.

Syntax error reference

This page explains 36 syntax error messages. Each card shows the message, code that produces it, the cause, and the fixed code.

Plain "invalid syntax"

SyntaxError: invalid syntax

Python says: SyntaxError: invalid syntax

Python could not read this line and does not say why. The cause is at the marked place or just before it, sometimes on the line above.

Go through the usual causes one by one.

  • A misspelled keyword, such as whille, esle or retrun.
  • A missing operator or comma between two values.
  • Two statements on one line with nothing between them.
  • A bracket or a quote left open on the line above.
  • Code from another language, or a terminal command.
Example with this error
x = 5 y = 6
Fixed
x = 5
y = 6

Common causes of "invalid syntax"

A reserved word used as a name

Python says: SyntaxError: invalid syntax

Words such as class, def, pass, from, import, in, is, global and return are part of the Python language. They cannot be used as variable names.

Pick another name, for example class_name instead of class.

Example with this error
class = "Math"
print(class)
Fixed
class_name = "Math"
print(class_name)

else if or elseif instead of elif

Python says: SyntaxError: expected ':'

Python spells it elif. The forms else if and elseif come from other languages. Python reads else, expects a colon right after it and stops at the next word.

Replace it with elif.

Example with this error
x = 5
if x > 3:
    print("big")
else if x > 1:
    print("medium")
Fixed
x = 5
if x > 3:
    print("big")
elif x > 1:
    print("medium")
  • Python 3.9: SyntaxError: invalid syntax

else or elif that does not belong to an if

Python says: SyntaxError: invalid syntax

else and elif must come right after the block of their if, with the same indentation as that if. Here another line stands between them, or the indentation differs, so Python finds an else that has no if.

Put the else directly under the if block and give it the same indentation as the if.

Example with this error
x = 5
if x > 3:
    print("big")
print("checked")
else:
    print("small")
Fixed
x = 5
if x > 3:
    print("big")
else:
    print("small")
print("checked")

Syntax from another language

Python says: SyntaxError: invalid syntax

This line uses syntax from JavaScript, Java, C or a similar language. Python has no ++ and no &&, no curly braces around blocks, no var and no type in front of a name.

Use the Python form: x += 1 instead of x++, and / or instead of && / ||, a colon and indentation instead of { }, # instead of // for a comment, and a plain name = value.

Example with this error
count = 0
if (count < 5) {
    count++
}
Fixed
count = 0
if count < 5:
    count += 1

A line that stops in the middle

Python says: SyntaxError: invalid syntax

The line ends with an operator. Python expects a value after it and finds the end of the line.

Finish the expression. To continue a long expression on the next line, wrap it in parentheses.

Example with this error
price = 10
total = price +
print(total)
Fixed
price = 10
total = price + 5
print(total)

pip install and python file.py typed inside Python

pip install requests is a command for the terminal: Command Prompt or PowerShell on Windows, Terminal on macOS and Linux. Python itself does not understand it. If the error report starts with File "<stdin>", line 1, the command was typed at the Python prompt >>>. Type exit() to leave Python, then run the command again. This playground cannot install packages; numpy and pandas are built in.

pip install gives "invalid syntax"

Python says: SyntaxError: invalid syntax

pip is a program that you run in a terminal. It is not Python code, so Python cannot read this line.

Run the command in a terminal window, not inside Python. If you see the >>> prompt, type exit() first. In your Python code keep only the import line.

Example with this error
pip install requests
In the terminal: pip install requests. In the Python file:
import requests

python file.py gives "invalid syntax"

Python says: SyntaxError: invalid syntax

python main.py is a terminal command that starts a program. Typed after the >>> prompt or inside a script, it is not valid Python.

Run it in a terminal window, not inside Python. If you see the >>> prompt, type exit() first.

Example with this error
python main.py

>>> copied together with the code

Python says: SyntaxError: invalid syntax

>>> is the prompt that the interactive Python shell prints before each line. It is not part of the code.

Remove >>> and the space after it from the start of each line.

Example with this error
>>> x = 5
>>> print(x)
Fixed
x = 5
print(x)

Messages where Python names the problem

SyntaxError: expected ':'

Python says: SyntaxError: expected ':'

A line that starts a block must end with a colon. This applies to if, elif, else, for, while, def, class, try and with. Python reached the end of the line and did not find the colon.

Add a colon at the end of that line.

Example with this error
x = 5
if x > 3
    print("big")
Fixed
x = 5
if x > 3:
    print("big")
  • Python 3.9 and older: SyntaxError: invalid syntax

SyntaxError: '(' was never closed

Python says: SyntaxError: '(' was never closed

An opening bracket has no closing partner. The same message exists for [ and {. Python points at the bracket that was opened, even when the code goes on for many lines after it.

Add the missing closing bracket. Count the brackets on that line: every ( needs a ), every [ needs a ], every { needs a }.

Example with this error
name = "Ann"
print("Hi, " + name
print("Bye")
Fixed
name = "Ann"
print("Hi, " + name)
print("Bye")
  • Python 3.9 and older: SyntaxError: unexpected EOF while parsing, when the bracket is still open at the end of the file
  • Python 3.9 and older: SyntaxError: invalid syntax, reported one line below, when more code follows the open bracket

SyntaxError: unmatched ')'

Python says: SyntaxError: unmatched ')'

There is a closing bracket with no opening bracket before it. Usually one bracket too many was typed.

Remove the extra closing bracket, or add the opening bracket that is missing.

Example with this error
x = 3
print(x))
Fixed
x = 3
print(x)

SyntaxError: closing parenthesis ')' does not match opening parenthesis '['

Python says: SyntaxError: closing parenthesis ')' does not match opening parenthesis '['

A bracket was opened with one kind and closed with another.

Close each bracket with its own kind: ( with ), [ with ], { with }.

Example with this error
nums = [1, 2, 3)
Fixed
nums = [1, 2, 3]

SyntaxError: unterminated string literal

Python says: SyntaxError: unterminated string literal (detected at line 1)

A string was opened with a quote and not closed before the end of the line. A common cause is an apostrophe inside a string written in single quotes: the apostrophe ends the string early.

Add the closing quote. If the text contains an apostrophe, put the string in double quotes.

Example with this error
print("Hello, world)
Fixed
print("Hello, world")
  • Python 3.9 and older: SyntaxError: EOL while scanning string literal

SyntaxError: unterminated triple-quoted string literal

Python says: SyntaxError: unterminated triple-quoted string literal (detected at line 2)

A string opened with three quotes runs to the end of the file. Everything after the opening quotes became part of the string.

Close the string with the same three quotes.

Example with this error
text = """Hello
print(text)
Fixed
text = """Hello"""
print(text)
  • Python 3.9 and older: SyntaxError: EOF while scanning triple-quoted string literal

SyntaxError: invalid syntax. Is this intended to be part of the string?

Python says: SyntaxError: invalid syntax. Is this intended to be part of the string?

The string contains the same kind of quote that surrounds it. The inner quote ends the string, and the text after it is no longer inside a string.

Use the other kind of quotes on the outside, or put a backslash before each inner quote.

Example with this error
print("She said "hi"")
Fixed
print('She said "hi"')
  • Python 3.13: SyntaxError: invalid syntax. Perhaps you forgot a comma?
  • Python 3.9: SyntaxError: invalid syntax

SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Python says: SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

A single = stores a value in a name. To compare two values in a condition, Python uses ==.

Write == in the condition.

Example with this error
x = 10
if x = 10:
    print("ten")
Fixed
x = 10
if x == 10:
    print("ten")
  • Python 3.9: SyntaxError: invalid syntax

SyntaxError: cannot assign to literal

Python says: SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

The left side of = must be a name that can hold a value. Here the left side is a number, a string, a function call or a calculation.

Put the name on the left and the value on the right. If you meant to compare, use ==.

Example with this error
score = 7
10 = score
Fixed
score = 10
  • Python 3.9 and older: SyntaxError: cannot assign to literal

SyntaxError: invalid syntax. Perhaps you forgot a comma?

Python says: SyntaxError: invalid syntax. Perhaps you forgot a comma?

Two values stand next to each other with nothing between them. Inside brackets Python expects a comma or an operator between values.

Add the comma. If you meant to join two pieces of text, use + or an f-string.

Example with this error
total = 3
print("Total:" total)
Fixed
total = 3
print("Total:", total)
  • Python 3.9 and older: SyntaxError: invalid syntax

SyntaxError: positional argument follows keyword argument

Python says: SyntaxError: positional argument follows keyword argument

In a function call the arguments written as name=value must come after the plain ones. Here a plain argument stands after a name=value one.

Move the plain arguments to the front, or give every argument a name.

Example with this error
print("a", sep="-", "b")
Fixed
print("a", "b", sep="-")
  • Python 3.4 and older: SyntaxError: non-keyword arg after keyword arg

SyntaxError: 'return' outside function

Python says: SyntaxError: 'return' outside function

return works only inside a function, that is inside a def block. Here it stands outside, often because the line lost its indentation.

Indent the return line so that it sits inside the def block.

Example with this error
def add(a, b):
    total = a + b
return total
Fixed
def add(a, b):
    total = a + b
    return total

SyntaxError: 'break' outside loop

Python says: SyntaxError: 'break' outside loop

break and continue work only inside a for or while loop. Here the line is outside the loop, often because of its indentation.

Indent the line so that it sits inside the loop body, or remove it.

Example with this error
for n in range(5):
    print(n)
break
Fixed
for n in range(5):
    print(n)
    break

SyntaxError: invalid decimal literal

Python says: SyntaxError: invalid decimal literal

Python found a number with letters attached to it. This happens when a name starts with a digit, or when a unit is written right after a number.

A name cannot start with a digit: write first_place, not 1st_place. Keep units out of the number: 100, not 100px.

Example with this error
1st_place = "Ann"
Fixed
first_place = "Ann"
  • Python 3.9: SyntaxError: invalid syntax

SyntaxError: leading zeros in decimal integer literals are not permitted

Python says: SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

A whole number cannot start with 0, except the number 0 itself.

Drop the leading zero: 7, not 07. If the zeros matter, as in a ZIP code or a phone number, keep the value as a string in quotes.

Example with this error
day = 07
Fixed
day = 7

SyntaxError: unexpected character after line continuation character

Python says: SyntaxError: unexpected character after line continuation character

Outside a string a backslash means that the line continues on the next one, and nothing may follow it on the same line. The usual causes are a backslash typed instead of / for division, or text left after the backslash.

For division use /. To continue a line, make the backslash its very last character, or wrap the expression in parentheses.

Example with this error
print(10 \ 2)
Fixed
print(10 / 2)

SyntaxError: invalid character

Python says: SyntaxError: invalid character '“' (U+201C)

The code contains a character that looks right but is not the plain keyboard one. Curly quotes, long dashes and invisible spaces come from word processors, chat apps and web pages.

Retype the marked character on the keyboard: straight quotes " or ' and a plain minus sign.

Example with this error
print(“Hello”)
Fixed
print("Hello")

SyntaxError: f-string: expecting '}'

Python says: SyntaxError: f-string: expecting '}'

Inside an f-string every { that starts a value needs a closing }.

Add the missing }.

Example with this error
name = "Ann"
print(f"Hello, {name")
Fixed
name = "Ann"
print(f"Hello, {name}")

SyntaxError: 'elif' block follows an 'else' block

Python says: SyntaxError: 'elif' block follows an 'else' block

else must be the last branch of an if statement. An elif cannot come after it.

Move the elif above the else.

Example with this error
x = 5
if x > 3:
    print("big")
else:
    print("small")
elif x > 1:
    print("medium")
Fixed
x = 5
if x > 3:
    print("big")
elif x > 1:
    print("medium")
else:
    print("small")
  • Python 3.13: SyntaxError: invalid syntax

SyntaxError: expected '('

Python says: SyntaxError: expected '('

A function definition needs parentheses after the name, even when the function takes no arguments.

Add () before the colon.

Example with this error
def greet:
    print("hi")
Fixed
def greet():
    print("hi")
  • Python 3.9: SyntaxError: invalid syntax

SyntaxError: expected 'except' or 'finally' block

Python says: SyntaxError: expected 'except' or 'finally' block

A try block must be followed by except or finally. Python reached the next statement, or the end of the file, and did not find one.

Add an except block right after the try block.

Example with this error
try:
    number = int("12")
print(number)
Fixed
try:
    number = int("12")
except ValueError:
    number = 0
print(number)
  • Python 3.9 and older: SyntaxError: unexpected EOF while parsing, when the try block is the last thing in the file
  • Python 3.9 and older: SyntaxError: invalid syntax, when more code follows the try block

Messages from older Python versions

Tutorials and old answers often quote messages that current Python no longer prints. These cards explain them. The tool on this page runs Python 3.14, so for the same code it shows the current message.

SyntaxError: unexpected EOF while parsing

EOF stands for end of file. Python reached the end of the code while something was still open. Python 3.9 and older print this message. Newer versions name the cause.

Look for a bracket that was never closed, most often in the last lines, or for a try block with no except. The same message appears when eval() receives an empty or cut-off string. Paste the code into the tool on this page: Python 3.14 names the open bracket and its line.

Example with this error
x = 5
print(x
Fixed
x = 5
print(x)
  • Python 3.9 and older: SyntaxError: unexpected EOF while parsing

SyntaxError: f-string expression part cannot include a backslash

In Python 3.11 and older the part of an f-string inside { } cannot contain a backslash, for example '\n'. Python 3.12 removed this limit.

Put the value with the backslash into a variable and use the variable inside the braces. Or run the code on Python 3.12 or newer.

Example with this error
items = ["a", "b"]
print(f"{'\n'.join(items)}")
Fixed
items = ["a", "b"]
newline = "\n"
print(f"{newline.join(items)}")
  • Python 3.11 and older: SyntaxError: f-string expression part cannot include a backslash

SyntaxError: f-string: unmatched '['

In Python 3.11 and older an f-string cannot reuse its own quote character inside { }. The inner quote ends the string early, and Python reports the bracket that stayed open: [ or (. Python 3.12 allows the same quotes inside.

Use the other kind of quotes inside the braces. Or run the code on Python 3.12 or newer.

Example with this error
data = {"key": 1}
print(f"{data["key"]}")
Fixed
data = {"key": 1}
print(f"{data['key']}")
  • Python 3.11 and older: SyntaxError: f-string: unmatched '['
  • Python 3.11 and older: SyntaxError: f-string: unmatched '('

SyntaxError: future feature annotations is not defined

The line from __future__ import annotations needs Python 3.7 or newer. This message means that the code is running on Python 3.6 or older.

Run the code with a newer Python. The command python --version in a terminal shows which version you have.

Example with this error
from __future__ import annotations
  • Python 3.6 and older: SyntaxError: future feature annotations is not defined

Indentation errors

Errors in the spaces at the start of a line have their own names, IndentationError and TabError.

IndentationError and TabError

Python says: IndentationError: expected an indented block after 'if' statement on line 2

This is an indentation problem. Python uses the spaces at the start of a line to decide which lines belong to a block.

Indent the lines of a block by 4 spaces, give all lines of one block the same indentation, and do not mix tabs with spaces.

Example with this error
x = 5
if x > 3:
print("big")
Fixed
x = 5
if x > 3:
    print("big")
  • Python 3.9 and older: IndentationError: expected an indented block

What this tool does not do

  • It does not fix the code. It explains the error and shows an example of the fix.
  • It reports the first syntax error only, because Python stops at the first one.
  • It does not run the code. Errors that happen while a program runs, such as NameError or TypeError, are not found here. Run the code in the Python Playground to see those.
  • It reads the code as Python 3.14. Code written for Python 2 shows errors.
  • It does not explain every possible message. For a message without its own card you get the text from Python, the line and general advice.

FAQ

What does "invalid syntax" mean in Python?

Python could not read a line of your code and cannot name the reason. The line number in the message shows where it stopped. The mistake is at that place or just before it.

Why is the error on a line that looks correct?

Python reports the place where it could not continue. In Python 3.9 and older a bracket left open on one line is reported on the next line. Check the line above for an open bracket or quote.

What does "unexpected EOF while parsing" mean?

Python reached the end of the code while a bracket or a block was still open. Python 3.9 and older print this message. Newer versions say which bracket was never closed.

Why do I get a pip install invalid syntax error?

pip install is a terminal command, not Python code. Leave the Python prompt with exit() and run the command in the terminal. Any pip command typed at the Python prompt gives the same Python pip invalid syntax error, and so does python -m pip install.

Why does print give a syntax error?

In Python 3 print is a function: write print("hello") with parentheses. print "hello" is Python 2 syntax.

What causes a Python for loop syntax error?

The usual causes are a missing colon at the end of the for line, a missing in between the variable and the sequence, and a loop body that is not indented.

Does the tool run my code?

No. It only parses the code, the way Python does before it runs a program.

Is my code uploaded?

No. The check happens in your browser.

Which Python version does it use?

Python 3.14. Messages from older versions are listed in the reference with the version they belong to.