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.
Your error
Check these first
- Look at the line above too. A bracket or quote left open on one line is often reported on the next.
- Colons and closings. Lines starting
if,for,while,defandclassend with:, and every(,[,{and quote is closed. - 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.
age = 20
if age >= 18
print("Adult")
SyntaxError: expected ':'
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.
total = (5 + 3
print(total)
SyntaxError: '(' was never closed
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'.
print("Hello)
SyntaxError: unterminated string literal (detected at line 1)
print("Hello")
Hello
4 A missing comma
Items in a list, a tuple or a function call are separated by commas.
numbers = [1, 2 3]
print(numbers)
SyntaxError: invalid syntax. Perhaps you forgot a comma?
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.
x = 5
if x = 5:
print("five")
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
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.
print(โHelloโ)
SyntaxError: invalid character 'โ' (U+201C)
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,globalandlambdabelong 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, andif x 5:โif x == 5:. - A command, not code.
pip install requestsandpython main.pygo 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 nothenordo, and no{ }around a block: a colon and indented lines. - A
forloop withoutin.for i range(5):โfor i in range(5):. - An
elseorelifaway from itsif. It comes straight after theifblock, at the same indentation, andelsecomes last. - Two statements on one line.
print("a") print("b"): put each on its own line. - Something left out.
x = 5 +โx = 5 + 1, andprint(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.
2nd_place = "Bo"
print(2nd_place)
SyntaxError: invalid decimal literal
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.
print("Hi"))
SyntaxError: unmatched ')'
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.
print "Hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
print("Hello")
Hello
'return' outside function
return only works inside a function. Usually the line lost its indentation: put it back under the def.
def add(a, b):
total = a + b
return total
print(add(2, 3))
SyntaxError: 'return' outside function
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.
for n in [3, 7, 9]:
print(n)
if n == 7:
break
SyntaxError: 'break' outside loop
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".
month = 08
print(month)
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
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.
try:
number = int("42")
print(number)
SyntaxError: expected 'except' or 'finally' block
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.
print(sep="-", "a", "b")
SyntaxError: positional argument follows keyword argument
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 /.
x = 10 \ 2
print(x)
SyntaxError: unexpected character after line continuation character
x = 10 / 2
print(x)
5.0
f-string: expecting '}'
Every { in an f-string needs its }, with a value or name between them.
name = "Ada"
print(f"Hi {name")
SyntaxError: f-string: expecting '}'
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.
import sqrt from math
print(sqrt(16))
SyntaxError: Did you mean to use 'from ... import ...' instead?
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.
def greet(greeting="Hi", name):
print(greeting, name)
greet(name="Ada")
SyntaxError: parameter without a default follows parameter with a default
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.
try:
number = int("abc")
except ValueError, TypeError:
number = 0
print(number)
SyntaxError: multiple exception types must be parenthesized
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".
x = 5
size = "big" if x > 3
print(size)
SyntaxError: expected 'else' after 'if' expression
x = 5
size = "big" if x > 3 else "small"
print(size)
big
Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: Hello, World!
- Other errors: AttributeError, FileNotFoundError, IndentationError, IndexError, KeyError, ModuleNotFoundError, NameError, RecursionError, TypeError, UnboundLocalError, ValueError, ZeroDivisionError