SyntaxError · Examples
Core Python

SyntaxError Examples

Short, runnable programs that show python syntaxerror in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python SyntaxError lesson.

1Reading lineno, offset and text from the error

The exception object carries the details Python prints in the traceback. offset is the 1-based column of the caret.

Reading lineno, offset and text from the error
source = "total = 10 +\nprint(total)"
try:
    compile(source, "main.py", "exec")
except SyntaxError as err:
    print("message:", err.msg)
    print("line:", err.lineno)
    print("column:", err.offset)
    print("code:", err.text.rstrip())
Expected outputmessage: invalid syntax
line: 1
column: 13
code: total = 10 +

2Drawing the caret yourself

Using the column number you can reproduce the little arrow Python prints under the problem.

Drawing the caret yourself
source = "if price = 5:\n    pass"
try:
    compile(source, "main.py", "exec")
except SyntaxError as err:
    print(err.text.rstrip())
    print(" " * (err.offset - 1) + "^")
    print(err.msg)
Expected outputif price = 5:
   ^
invalid syntax. Maybe you meant '==' or ':=' instead of '='?

3An unclosed bracket is reported on its opening line

The mistake looks like it is on the last line, but Python points back to where the bracket was opened.

An unclosed bracket is reported on its opening line
source = (
    "orders = [\n"
    "    10,\n"
    "    25,\n"
    "total = sum(orders)\n"
)
try:
    compile(source, "main.py", "exec")
except SyntaxError as err:
    print(f"line {err.lineno}: {err.msg}")
Expected outputline 1: '[' was never closed

4Missing comma between strings is silent

Two adjacent strings are glued together, so no SyntaxError appears, but the list has one item fewer than you wanted.

Missing comma between strings is silent
colors = ["red" "blue", "green"]
print(colors)
print(len(colors))

colors = ["red", "blue", "green"]
print(len(colors))
Expected output['redblue', 'green']
2
3

5Validating a formula before using it

ast.parse checks that text is valid Python without running it, which is useful when a user types an expression.

Validating a formula before using it
import ast

def is_valid_formula(text):
    try:
        ast.parse(text, mode="eval")
        return True
    except SyntaxError:
        return False

for formula in ["2 * (3 + 4)", "2 *+ (3", "price - discount", "10 //"]:
    print(f"{formula!r:16} valid? {is_valid_formula(formula)}")
Expected output'2 * (3 + 4)'    valid? True
'2 *+ (3'        valid? False
'price - discount' valid? True
'10 //'          valid? False

6Python 2 print versus Python 3

Old tutorials write print without brackets. Python 3 gives a helpful message with the fix.

Python 2 print versus Python 3
old_style = 'print "Welcome back"'
try:
    compile(old_style, "old.py", "exec")
except SyntaxError as err:
    print(err.msg)

compile('print("Welcome back")', "new.py", "exec")
print("The new style compiles fine")
Expected outputMissing parentheses in call to 'print'. Did you mean print(...)?
The new style compiles fine

Practise next

Python SyntaxError exercises → Back to the lesson

Python Syntax examplesPython Exceptions: try, except, else and finally examplesPython NameError examplesPython IndentationError examples