PythonMastery
reference 2 min read · lesson 70 of 80 in Errors

SyntaxError: expected ':'

1 · The lesson

read

What this error means

A line that opens a block is missing its colon. In Python, every line that has an indented block under it ends with :. That includes if, elif, else, for, while, def, class, try, except, finally, with and match/case. The colon tells Python "the body starts on the next line". Without it, Python stops before running anything. The ^ points at the end of the line where the colon should go.

When you see it

python
  File "main.py", line 2
    if age >= 18
                ^
SyntaxError: expected ':'

The same message for a function, a loop or an else:

python
  File "main.py", line 1
    def greet(name)
                   ^
SyntaxError: expected ':'
python
  File "main.py", line 4
    else
        ^
SyntaxError: expected ':'

Python 3.9 and older did not have this message. They said only SyntaxError: invalid syntax for the same mistake.

Why it happens

1. You forgot it. It's the most common typo for people coming from languages that use { } or then, and for everyone typing quickly.

python
for n in range(3)
    print(n)

2. else and try lines feel finished. A bare else or try has nothing after it, so the colon is easy to miss:

python
x = 1
if x:
    print("yes")
else
    print("no")

3. A long line hides the end. After a long call, like with open("data.csv", encoding="utf-8") as f, the end of the line is easy to miss.

A colon in the wrong place, like def greet(name:), or a semicolon instead of a colon, like if x > 3;, gives a different message: SyntaxError: invalid syntax. The fix is the same: put a : at the very end of the line.

How to fix it

Add the colon at the end of the line the ^ points at:

python
age = 20
if age >= 18:
    print("adult")      # adult

def greet(name):
    print("Hi", name)

greet("Ada")            # Hi Ada

for n in range(3):
    print(n)            # 0, 1, 2 on separate lines

Check every part of an if chain. Each elif and else needs its own colon:

python
score = 72
if score >= 90:
    grade = "A"
elif score >= 70:
    grade = "B"
else:
    grade = "C"
print(grade)            # B

A one-line block still needs the colon. Writing the body on the same line is allowed, but the colon stays:

python
x = 5
if x > 3: print("big")  # big

An unclosed bracket gives a different message, SyntaxError: '(' was never closed, even when the colon is missing too. Fix the bracket first: see SyntaxError: '(' was never closed.

When you'd see this in real code

  • class Config written without the colon when adding a new class at the top of a file.
  • A with open("data.csv") as f line, where the colon is easy to drop after a long call.
  • try and except ValueError blocks added around old code in a hurry.
  • A match statement (Python 3.10+): both match command and each case "quit" line need a colon.

See Also

Found this useful? Share it with a friend who’s learning Python.