SyntaxError · Exercises
Core Python

SyntaxError Exercises

4 exercises that build on the Python SyntaxError lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A SyntaxError means Python could not parse your code because it breaks the language's grammar, so the whole file is rejected before any line runs. By the end you can read a SyntaxError message and caret, spot the six most common grammar mistakes and fix each one. You will practise: Fix the two syntax errors; Predict the compile results; Find the broken line; Report broken files.

0 / 4 completed

SyntaxError practice exercises

1. Fix the two syntax errors

Fix the bug Easy

This program should print Total: 19.5, but Python rejects it before running anything. There are two grammar mistakes: fix both. total_price(prices) must return the sum and basket must stay [4.5, 3, 12].

Your code
def total_price(prices)
    return sum(prices)

basket = [4.5, 3, 12
print("Total:", total_price(basket))

2. Predict the compile results

Predict the output Easy

Read the code and type exactly what it prints. Remember that Python reports an unclosed bracket on the line where it was opened. Then press Check.

Read this code
snippets = [
    "x = 10",
    "if x > 5",
    "a = 1\nb = [2,\n3",
    "print('ok')",
]

for source in snippets:
    try:
        compile(source, "<snippet>", "exec")
        print("ok")
    except SyntaxError as err:
        print("error on line", err.lineno)

3. Find the broken line

Write code Medium

Write syntax_error_line(source) that takes Python code as a string and returns the line number (an int) where Python reports a SyntaxError, or None if the code is valid. Use compile() and catch SyntaxError. Do not run the code.

Your code
def syntax_error_line(source):
    return None

print(syntax_error_line("if x\n    pass"))

4. Report broken files

Write code Hard

Write find_errors(files) where files maps a file name to its source text. Return a list of (name, line_number) tuples for every file that has a SyntaxError, sorted by file name. Files with valid code are left out, and if nothing is broken the result is an empty list.

Your code
def find_errors(files):
    return []

print(find_errors({"ok.py": "x = 1", "bad.py": "if x\n    pass"}))

Next lessonPython IndentationError

More Python SyntaxError examples · All Python exercises