Python errors / SyntaxError

SyntaxError: invalid syntax

Python couldn't read your code, so none of it ran. The mistake is on the line the message points to, or just above it.

SyntaxError: invalid syntax

Check these first

  1. Look at the line above too. A bracket or quote left open on one line is often reported on the next.
  2. Colons and closings. Lines starting if, for, while, def and class end with :, and every (, [, { and quote is closed.
  3. Copied code. Code copied from a web page or a document can bring curly quotes โ€œ โ€ or long dashes โ€“, which Python can't read.

Causes and fixes

1 A missing colon

A line that starts a block (if, for, while, def, class, else) has to end with a colon. And else if is written elif in Python.

Broken
age = 20
if age >= 18
    print("Adult")
SyntaxError: expected ':'
Fixed
age = 20
if age >= 18:
    print("Adult")
Adult

2 A bracket that's never closed

Every (, [ and { needs its own closing bracket, of the same kind. Count them on the line the message names.

Broken
total = (5 + 3
print(total)
SyntaxError: '(' was never closed
Fixed
total = (5 + 3)
print(total)
8

3 A quote that's never closed

A string has to end with the same quote it starts with: "Hello" or 'Hello'.

Broken
print("Hello)
SyntaxError: unterminated string literal (detected at line 1)
Fixed
print("Hello")
Hello

4 A missing comma

Items in a list, a tuple or a function call are separated by commas.

Broken
numbers = [1, 2 3]
print(numbers)
SyntaxError: invalid syntax. Perhaps you forgot a comma?
Fixed
numbers = [1, 2, 3]
print(numbers)
[1, 2, 3]

5 = instead of ==

One = stores a value. To compare two values, as in an if, use ==. When you do mean to store, the name goes on the left: x = 5, not 5 = x.

Broken
x = 5
if x = 5:
    print("five")
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Fixed
x = 5
if x == 5:
    print("five")
five

6 Characters copied from a web page

Web pages and word processors bring characters that look right but that Python can't read: curly quotes โ€œ โ€, long dashes โ€“ and invisible non-breaking spaces. Retype them in the editor: ", - and a plain space.

Broken
print(โ€œHelloโ€)
SyntaxError: invalid character 'โ€œ' (U+201C)
Fixed
print("Hello")
Hello

Other messages

More messages SyntaxError can show. Open yours for what it means and how to fix it.

invalid syntax

Python met a word or symbol it didn't expect there, and can't say more. It's usually one of these, on the line it points to or the one above.

  • A Python word used as a name. class, pass, from, in, is, def, return, global and lambda belong to Python: pass = "1234" โ†’ password = "1234".
  • A space in a name. my score = 10 โ†’ my_score = 10.
  • Text without quotes. name = Ada Lovelace โ†’ name = "Ada Lovelace".
  • Two values with nothing between them. greeting = "Hi " name โ†’ greeting = "Hi " + name, and if x 5: โ†’ if x == 5:.
  • A command, not code. pip install requests and python main.py go in a terminal, not in the program: delete the line. In code copied from the Python shell, delete the >>> at the start of each line.
  • Symbols from other languages. i++ โ†’ i += 1, && โ†’ and, || โ†’ or, ! โ†’ not, === โ†’ ==. Comments start with #, not //.
  • Words from other languages. function add(a, b): โ†’ def add(a, b):, for item of items: โ†’ for item in items:, x => x * 2 โ†’ lambda x: x * 2. Python needs no then or do, and no { } around a block: a colon and indented lines.
  • A for loop without in. for i range(5): โ†’ for i in range(5):.
  • An else or elif away from its if. It comes straight after the if block, at the same indentation, and else comes last.
  • Two statements on one line. print("a") print("b"): put each on its own line.
  • Something left out. x = 5 + โ†’ x = 5 + 1, and print(1,, 2) โ†’ print(1, 2).
invalid decimal literal

A name can't start with a digit, and a number can't have letters stuck to it. Spell the name out, or put an operator between the number and the name: 5 * apples.

Broken
2nd_place = "Bo"
print(2nd_place)
SyntaxError: invalid decimal literal
Fixed
second_place = "Bo"
print(second_place)
Bo
unmatched ')'

There's a closing bracket with no opening one before it, often an extra one at the end of the line.

Broken
print("Hi"))
SyntaxError: unmatched ')'
Fixed
print("Hi")
Hi
Missing parentheses in call to 'print'

That's Python 2. In Python 3, print is a function: put what it prints in brackets.

Broken
print "Hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
Fixed
print("Hello")
Hello
'return' outside function

return only works inside a function. Usually the line lost its indentation: put it back under the def.

Broken
def add(a, b):
    total = a + b
return total

print(add(2, 3))
SyntaxError: 'return' outside function
Fixed
def add(a, b):
    total = a + b
    return total

print(add(2, 3))
5
'break' outside loop

break and continue only work inside a for or while loop. Indent them inside it.

Broken
for n in [3, 7, 9]:
    print(n)
if n == 7:
    break
SyntaxError: 'break' outside loop
Fixed
for n in [3, 7, 9]:
    print(n)
    if n == 7:
        break
3
7
leading zeros in decimal integer literals are not permitted

A whole number can't start with 0. Write 8, or keep the zero in text: "08".

Broken
month = 08
print(month)
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
Fixed
month = 8
print(month)
8
expected 'except' or 'finally' block

A try block needs an except (or finally) block right after it, at the same indentation.

Broken
try:
    number = int("42")
print(number)
SyntaxError: expected 'except' or 'finally' block
Fixed
try:
    number = int("42")
except ValueError:
    number = 0
print(number)
42
positional argument follows keyword argument

In a call, plain values come first and name=value ones last.

Broken
print(sep="-", "a", "b")
SyntaxError: positional argument follows keyword argument
Fixed
print("a", "b", sep="-")
a-b
unexpected character after line continuation character

A \ at the very end of a line carries it on to the next; anywhere else it's an error. To divide, use /.

Broken
x = 10 \ 2
print(x)
SyntaxError: unexpected character after line continuation character
Fixed
x = 10 / 2
print(x)
5.0
f-string: expecting '}'

Every { in an f-string needs its }, with a value or name between them.

Broken
name = "Ada"
print(f"Hi {name")
SyntaxError: f-string: expecting '}'
Fixed
name = "Ada"
print(f"Hi {name}")
Hi Ada
Did you mean to use 'from ... import ...' instead?

Python writes it the other way round: from module import name.

Broken
import sqrt from math
print(sqrt(16))
SyntaxError: Did you mean to use 'from ... import ...' instead?
Fixed
from math import sqrt
print(sqrt(16))
4.0
parameter without a default follows parameter with a default

In a def, parameters with a default value go after the ones without.

Broken
def greet(greeting="Hi", name):
    print(greeting, name)

greet(name="Ada")
SyntaxError: parameter without a default follows parameter with a default
Fixed
def greet(name, greeting="Hi"):
    print(greeting, name)

greet("Ada")
Hi Ada
multiple exception types must be parenthesized

To catch several errors with one except, put them in brackets.

Broken
try:
    number = int("abc")
except ValueError, TypeError:
    number = 0
print(number)
SyntaxError: multiple exception types must be parenthesized
Fixed
try:
    number = int("abc")
except (ValueError, TypeError):
    number = 0
print(number)
0
expected 'else' after 'if' expression

A value chosen with if on one line needs an else part too: "big" if x > 3 else "small".

Broken
x = 5
size = "big" if x > 3
print(size)
SyntaxError: expected 'else' after 'if' expression
Fixed
x = 5
size = "big" if x > 3 else "small"
print(size)
big

Still stuck?