SyntaxError: expected ':'
What it means
Lines that start a block, such as if, elif, else, for, while, def and class lines, must end with a colon. Python reached the end of one of these lines without finding it.
1. Forgetting the colon after an `if`
This raises the error
Broken
temperature = 31
if temperature > 30
print("It is a hot day")
Output
Traceback (most recent call last):
File "<exec>", line 2
if temperature > 30
^
SyntaxError: expected ':'The fix
Fixed
temperature = 31
if temperature > 30:
print("It is a hot day")
Output
It is a hot day
The colon marks the end of the condition and the start of the indented block below it.
2. Forgetting the colon after `def` or `for`
This raises the error
Broken
def greet(name)
print("Hello,", name)
greet("Ada")
Output
Traceback (most recent call last):
File "<exec>", line 1
def greet(name)
^
SyntaxError: expected ':'The fix
Fixed
def greet(name):
print("Hello,", name)
greet("Ada")
Output
Hello, Ada
A function definition needs the colon after its closing bracket, just like for, while and class lines do.
3. Writing `else if` instead of `elif`
This raises the error
Broken
x = 3
if x > 5:
print("big")
else if x > 2:
print("medium")
Output
Traceback (most recent call last):
File "<exec>", line 4
else if x > 2:
^^
SyntaxError: expected ':'The fix
Fixed
x = 3
if x > 5:
print("big")
elif x > 2:
print("medium")
Output
medium
Python spells it elif. After else, Python expects the colon straight away, so the if that follows looks like a missing colon.
When you see this error, check
- Check the end of every
if,elif,else,for,while,def,class,try,exceptandwithline for a colon. - Write
elif, notelse if. - Use a colon
:, not a semicolon;. - Put the colon after the closing bracket:
def greet(name):, notdef greet(name:).
Related errors
All Python errors · How to read a traceback · Step through your code