Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python  Module 1 – Getting started: install, run and read Python

Read error messages and tracebacks calmly

Read a Python traceback from the bottom up, recognise the errors beginners meet most often, and use the clearer messages of Python 3.14 to fix the failing line.

Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Read a traceback from the bottom up to find the failing line
  • Predict whether a file runs at all when it has a syntax error
  • Recognise the most common beginner exceptions and their usual causes
  • Use help(), the documentation and minimal examples to get unstuck

Before you start

What you’ll learn · Before you start

What you will learn

  • Read a traceback from the bottom up to find the failing line
  • Predict whether a file runs at all when it has a syntax error
  • Recognise the most common beginner exceptions and their usual causes
  • Use help(), the documentation and minimal examples to get unstuck

Before you start

On this page

One misspelt item, cofee, stops this lesson’s billing program with an eleven-line report, and the typo is easy to find in seconds once you know which line of the report to read first.

When a program fails, Python stops and prints a traceback: The report Python prints when an exception ends a program: the calls that led to the failing line, oldest first, and on the last line the exception's type and message. More in “Handling exceptions with try and except”. The first few look alarming, but a traceback is a precise report with three parts: what went wrong, the line where it happened, and the chain of calls that led there. Reading one in that order, from the bottom up, is the quickest way to find most bugs.

Read it from the bottom up

This program adds up two bills. The first one works; the second has a typo in its order:

A traceback through three functions Python · bill.py
prices = {"tea": 30, "toast": 45, "coffee": 60}


def line_total(item, quantity):
    return prices[item] * quantity


def bill(order):
    total = 0
    for item, quantity in order:
        total += line_total(item, quantity)
    return total


print("First bill:", bill([("tea", 2), ("toast", 1)]))
print("Second bill:", bill([("tea", 1), ("cofee", 2)]))

Output (exit status 1)

First bill: 105

Printed as an error (standard error)

Traceback (most recent call last):
  File "bill.py", line 16, in <module>
    print("Second bill:", bill([("tea", 1), ("cofee", 2)]))
                          ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "bill.py", line 11, in bill
    total += line_total(item, quantity)
             ~~~~~~~~~~^^^^^^^^^^^^^^^^
  File "bill.py", line 5, in line_total
    return prices[item] * quantity
           ~~~~~~^^^^^^
KeyError: 'cofee'

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bill.py

Start at the last line and work upwards:

  1. The last line names the exception and gives its message. KeyError: 'cofee' says that a dictionary was asked for a key it does not have, and the message is that key.
  2. The frame just above it shows where it happened: File "bill.py", line 5, in line_total, then the line itself. The ~ and ^ marks under it pick out the part of the line that failed, the lookup prices[item].
  3. Each frame higher up is a call that led there. bill() called line_total() on line 11, and the file’s top level (<module>) called bill() on line 16. “Most recent call last” means the frames run from the first call down to the line that failed.

Each block of two or three lines in the report is one frame: The record of one function call that has not finished: its local variables and the place to carry on when the call it is waiting for returns. More in “Recursion, the call stack and its limits”, a call that had not finished when the error happened. Step through the calls of the second bill, and the error’s way back up them:

Interactive · message by message The calls behind the traceback of bill.py Step through the second bill, call by call, then watch the KeyError travel back up the calls that led to it.
The calls behind the traceback of bill.py, step 8 of 8. Messages so far: The file's top level to bill(): bill(second order); bill() to line_total(): line_total('tea', 1); line_total() to bill(): returns 30; bill() to line_total(): line_total('cofee', 2); line_total() to bill(): KeyError: 'cofee'; bill() to The file's top level: KeyError: 'cofee'.The file's top level<module>, line 16bill()line 11line_total()line 5bill(second order)line_total('tea', 1)returns 30line_total('cofee', 2)KeyError: 'cofee'KeyError: 'cofee'

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. Line 16 calls bill(). The first bill has printed 105. Now line 16 calls bill() with the second order: one tea, and two of cofee, spelt with one f.
  2. bill() calls line_total(). Inside bill(), line 11 calls line_total() for the first item. tea is in the price list, so the lookup on line 5 works.
  3. 30 comes back. line_total() returns 30, one tea at 30, and bill() adds it to the total.
  4. The second item. Line 11 runs again, now for the second item of the order.
  5. The lookup fails. Line 5 looks up prices['cofee']. There is no such key, so Python raises KeyError with the key as its message, and line_total() stops at once.
  6. The error leaves line_total(). Nothing in line_total() handles the error, so it leaves the function and arrives in bill(), at line 11, where the call was made. bill() stops too.
  7. Up to the top level. bill() does not handle it either, so the error reaches the file's top level at line 16. Nothing is left to handle it, and the program ends.
  8. The traceback lists the way down. Python prints the calls in the order they were made, line 16, then line 11, then line 5, with the exception last. Read it from the bottom: the error, the line that failed, then each call that led there.

The line that failed is not always the line to fix. Nothing is wrong with line_total(): it was given a bad value. Keep reading upwards until you reach the line where the bad value came from, here the order on line 16. Notice too that the first bill was printed: everything before the failing line ran normally. Press Edit, correct cofee on line 16 and run it: both bills print, and the second is 150.

Key idea

Read a traceback from the bottom: the last line says what went wrong, the frame above it says where, and the frames higher up say how the program got there. The line to fix is where the bad value came from.

When the failing frames are not your code

If you pass something wrong to a function of the standard library or of a package, the last frames are inside that function’s own files:

A traceback that ends in the standard library Python · bad_json.py
import json

settings_text = "{'theme': 'dark'}"
settings = json.loads(settings_text)
print("Theme:", settings["theme"])

Output (exit status 1)

Printed as an error (standard error)

Traceback (most recent call last):
  File "bad_json.py", line 4, in <module>
    settings = json.loads(settings_text)
  File "…/lib/python3.14/json/__init__.py", line 352, in loads
    return _default_decoder.decode(s)
           ~~~~~~~~~~~~~~~~~~~~~~~^^^
  File "…/lib/python3.14/json/decoder.py", line 345, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "…/lib/python3.14/json/decoder.py", line 361, in raw_decode
    obj, end = self.scan_once(s, idx)
               ~~~~~~~~~~~~~~^^^^^^^^
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bad_json.py

The frames under …/lib/python3.14/json/ belong to Python’s json module (the … stands for the folder Python is installed in, which differs from one computer to the next). Do not go looking for a bug there. Find the last frame that is in your own file, line 4, where json.loads() was called, and check what you gave it. The message says the rest: JSON needs double quotes around names, so the text should have been '{"theme": "dark"}'.

JSON Validator Paste a JSON text to see the exact line and column where it stops being valid JSON.

Checkpoint

Check: Reading a traceback from the bottom up

  1. Question 1 of 2 Where do you start reading a traceback?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: At the last line, which names the exception and its message

    A traceback reads best from the bottom up: the exception and its message, then the frame of the line that failed, then the calls above it that led there.

  2. Question 2 of 2 bill.py stops with KeyError: 'cofee', raised on line 5 inside line_total(). Which line do you change to fix the second bill?

    Choose one answer.

    A hint

    Is anything wrong with the lookup itself?

    Show the answer: Question 2 of 2

    Answer: Line 16, where the order misspells coffee

    The line that failed is not always the line to fix. Line 5 did its job; the value it was given came from the order on line 16, which is where the typo is.

A SyntaxError means nothing ran

Python reads a whole file before running any of it. When the grammar is wrong, it reports a SyntaxError and runs nothing at all, not even the lines above the mistake:

A misspelt keyword Python · typo_keyword.py
print("This line never runs")


def greeting(name):
    retrun "Hello, " + name


print(greeting("Asha"))

Output (exit status 1)

Printed as an error (standard error)

  File "typo_keyword.py", line 5
    retrun "Hello, " + name
    ^^^^^^
SyntaxError: invalid syntax. Did you mean 'return'?

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 typo_keyword.py

There is no “Traceback (most recent call last)” line this time, because no call happened: the file never started. The first line, a print(), printed nothing for the same reason. Press Edit, correct retrun to return and run it: both print() calls now run, the first one included.

Version note

New in Python 3.14: when a word looks like a misspelt keyword, the message suggests the keyword, as in Did you mean 'return'? above. Python 3.13 and older say only invalid syntax.

Sometimes the line Python shows looks perfectly fine. The cause is then usually earlier, often a bracket or a quote that was opened and never closed. Python points at where it was opened:

A bracket that was never closed Python · unclosed.py
marks = [72, 88, 95
print(sum(marks) / len(marks))

Output (exit status 1)

Printed as an error (standard error)

  File "unclosed.py", line 1
    marks = [72, 88, 95
            ^
SyntaxError: '[' was never closed

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 unclosed.py

The list on line 1 never gets its ]. Inside brackets Python keeps reading on the following lines, so it reaches the end of the file still inside the list, and reports the line where the list began. IndentationError, for lines indented in a way that does not match the blocks around them, is a kind of SyntaxError too and is reported the same way, before anything runs.

Checkpoint

Check: A SyntaxError means nothing ran

  1. Question 1 of 2 typo_keyword.py has print("This line never runs") on line 1 and retrun on line 5. What does it print before the error report?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Nothing, because the SyntaxError stops the file before any line runs

    A SyntaxError is found while Python compiles the whole file, before anything runs, so even the print() on line 1 never prints. The report shows the file and the line, without the Traceback line.

  2. Question 2 of 2 Python reports a SyntaxError on line 12, and line 12 looks perfectly correct. Where do you look next?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Above it, for a bracket or a quote that was opened and never closed

    When the line shown looks fine, the cause is usually earlier: a bracket or a quote opened and never closed. Since Python 3.10 an unclosed bracket is reported at the line where it was opened.

Each common exception points at one kind of mistake

Each of these eight lines makes a different mistake. The program runs them one at a time and prints the last line of each traceback, so you can see the exact messages of this version of Python:

Eight common mistakes and their messages Python · error_gallery.py
import traceback

# Eight one-line mistakes. exec() runs each line as a tiny program and the error is caught,
# so you see the last line of every traceback, exactly as Python prints it.
mistakes = [
    "print(scroe)",
    '"3" + 4',
    'int("three")',
    "[10, 20, 30][3]",
    '{"tea": 30}["coffee"]',
    '"text".uper()',
    "1 / 0",
    "import numpyy",
]
for code in mistakes:
    try:
        exec(code)
    except Exception as error:
        last_line = traceback.format_exception_only(error)[-1].strip()
        print(f"{code:<24}{last_line}")

Output

print(scroe)            NameError: name 'scroe' is not defined
"3" + 4                 TypeError: can only concatenate str (not "int") to str
int("three")            ValueError: invalid literal for int() with base 10: 'three'
[10, 20, 30][3]         IndexError: list index out of range
{"tea": 30}["coffee"]   KeyError: 'coffee'
"text".uper()           AttributeError: 'str' object has no attribute 'uper'. Did you mean: 'upper'?
1 / 0                   ZeroDivisionError: division by zero
import numpyy           ModuleNotFoundError: No module named 'numpyy'

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 error_gallery.py

When a name or an attribute is misspelt and something close to it exists, Python adds Did you mean …?, as for uper above. Press Edit, add a mistake of your own to the list, such as '"5" * "2"', and run it to see its message. What each error usually means, and where to look first:

Error It usually means Look first at
NameError A name is used that was never assigned, or is misspelt The spelling, and whether the line that assigns it ran first
TypeError A value of the wrong type for the operation, such as text plus a number The types involved: convert with int(), float() or str()
ValueError The right type with a value that does not fit, such as int("three") The data, often what the user typed or a file contained
IndexError A position past the end of a list: the last one is len(items) - 1 A loop or a calculation that goes one step too far
KeyError A dictionary has no such key; the message is the key The key’s spelling, or use .get() when it may be missing
AttributeError The object has no method or attribute of that name The spelling, and the object’s type: print(type(value))
ZeroDivisionError Division by zero Counts and lengths that can be 0, such as an empty list
ModuleNotFoundError No module of that name for this Python The spelling, and whether the package is installed in the environment you run
IndentationError Indentation that does not match the blocks A missing indented line after a colon, or tabs mixed with spaces
RecursionError A function kept calling itself, by default about 1,000 levels deep The case that should stop the recursion

A common mistake: a file named after a module

Name your own file after a module you import, such as random.py, and Python imports your file instead of the module. Python 3.13 and newer notice and say so:

A file called random.py Python · shadow/random.py
import random

print("Your dice roll:", random.randint(1, 6))

Output (exit status 1)

Printed as an error (standard error)

Traceback (most recent call last):
  File "random.py", line 1, in <module>
    import random
  File "random.py", line 3, in <module>
    print("Your dice roll:", random.randint(1, 6))
                             ^^^^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'randint' (consider renaming 'random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 random.py

The script imports itself as random, so random.randint does not exist. The message even names the file to rename: call it dice.py and import random finds the standard library’s module again. Python 3.12 and older report the same mistake only as a “partially initialized module” and a possible circular import.

Checkpoint

Check: What the common exceptions point at

  1. Question 1 of 2 Which exception does int("three") raise?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: ValueError

    int("three") has the right type of argument with a value that does not fit, which is what ValueError means. The message names the text: invalid literal for int() with base 10: 'three'.

  2. Question 2 of 2 marks = [72, 88, 95]. Which exception does marks[3] raise, and why?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: IndexError, because the positions of a 3-item list are 0, 1 and 2

    A list of 3 items has positions 0 to 2, so marks[3] raises IndexError: list index out of range. Look for a loop or a calculation that goes one step too far.

Python’s messages grew clearer, release by release

Python 3.14 improved several other messages too. Using a list as a dictionary key fails, as before, because keys must be hashable: A value that can be a dict key or a set item, because its hash never changes while it exists: numbers, strings and tuples of hashable values are hashable; lists, dicts and sets are not. More in “functools: cache, partial, reduce and more” and a list, which can change, is not; but the message now says what you tried to do:

A list as a dictionary key Python · unhashable.py
stock = {}
stock[["tea", "toast"]] = 2

Output (exit status 1)

Printed as an error (standard error)

Traceback (most recent call last):
  File "unhashable.py", line 2, in <module>
    stock[["tea", "toast"]] = 2
    ~~~~~^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 unhashable.py

Version note

Python 3.13 and older stop at TypeError: unhashable type: 'list'. Two older improvements show in every traceback of this lesson: since Python 3.11 the ~ and ^ marks point at the exact part of a line that failed (PEP 657), and since Python 3.13 tracebacks in a terminal are in colour, which the environment variables PYTHON_COLORS=0 and NO_COLOR=1 turn off. The pages of What’s New list every improvement, version by version.

Each feature release since 3.10 has added messages like these, so the same mistake reads differently on an older Python. Walk through what each release changed:

Timeline · 5 events in order How Python's error messages grew clearer, release by release Walk through the releases in order. Each one changed what a traceback or a SyntaxError tells you.
  1. 3.10

    Unclosed brackets and expected colons SyntaxError

    A bracket that is never closed is reported where it opens, as '[' was never closed, instead of at the end of the file, and a missing colon gets expected ':'. NameError and AttributeError add Did you mean …? when a close name exists.

  2. 3.11

    Marks under the part that failed tracebacks

    Tracebacks put ~ and ^ under the exact part of a line that failed, such as prices[item] inside a longer expression (PEP 657).

  3. 3.12

    Missing imports suggested

    A NameError for a standard module you forgot to import says Did you forget to import 'sys'?, and a failed from-import suggests the name you meant.

  4. 3.13

    Colour, and files named like modules

    Tracebacks in a terminal are in colour. A script named like a standard module, such as random.py, is told to consider renaming it, and a misspelt keyword argument gets Did you mean …?

  5. 3.14

    Misspelt keywords and unhashable keys this track

    A misspelt keyword such as retrun gets Did you mean 'return'?, and a list used as a dict key gets cannot use 'list' as a dict key. These are the messages this lesson's examples print.

The timeline has 5 events, from 3.10 to 3.14.

On the Python you run, the newest messages are the help you get. On an older one, such as the Python of a server, expect only the older wording, and read the marked part of the line yourself.

Checkpoint

Check: Error messages by Python version

  1. One question On Python 3.13, the line retrun "Hello, " + name is in a function. What does the SyntaxError say?

    Choose one answer.

    Show the answer: One question

    Answer: invalid syntax, without a suggestion

    Python 3.14 added Did you mean 'return'? to this SyntaxError. On 3.13 and older the same file stops with only SyntaxError: invalid syntax, so on an older Python, read the marked word for typos yourself.

  1. Read the last line slowly and look the exception up on the Built-in Exceptions page of the Python documentation. In the shell, help() shows the documentation of a function, a type or a module, and issubclass() tells you which broader kind of error an exception belongs to:

    Asking Python itself Python console · help_session.pycon
    >>> help(len)
    Help on built-in function len in module builtins:
    
    len(obj, /)
        Return the number of items in a container.
    
    >>> issubclass(KeyError, LookupError)
    True
    >>> issubclass(ModuleNotFoundError, ImportError)
    True

    This session was replayed with Python 3.14.8 on macOS 26 arm64, and it printed exactly what is shown.

  2. Print what you have. Just above the failing line, add print(repr(value), type(value)) for the values it uses. Most surprises are a value of a different type, or text with a space you cannot see.

  3. Make a minimal example. Copy the program and delete everything that is not needed to make the error happen, until only a few lines are left. You often find the bug on the way; if not, those few lines are what you show when you ask for help.

  4. Search for the last line, leaving out the names and values that are particular to your program.

Step through the four steps on the KeyError of bill.py:

Interactive · stage by stage Four steps that get you unstuck Step through the steps on the KeyError of bill.py. Each step either finds the bug or leaves you a smaller problem.
Four steps that get you unstuck, step 5 of 5. Showing Read the last line, Print the values it uses, Make a minimal example, Search for the last line. In focus: Read the last line.a new error? start againRead the last lineKeyError: 'cofee'Print the values it usesrepr(value), type(value)Make a minimal examplea few lines that still failSearch for the last linewithout your own namesnext traceback

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Read the last line. KeyError: 'cofee' says what went wrong: a dictionary has no key 'cofee'. The message is the key, so the next question is where that key came from.
  2. Print what you have. Above the failing line, print(repr(item), type(item)) shows the exact value. repr() shows what print() hides, such as the space at the end of 'coffee ' in print_values.py.
  3. Shrink the program. Delete everything the error does not need. bill.py shrinks to two lines, a dict and one lookup, that still raise the same KeyError: that is minimal.py.
  4. Search for the last line. Search for KeyError with what the code was doing, a dictionary lookup, and leave out your own names and values, such as cofee and line_total.
  5. A new error, the same steps. Fixing one bug often lets the program run on into the next. Start again from the new traceback's last line.

Here is step 2 on a value read from a file: print() shows the item as coffee, and only repr() shows the space after it that makes the lookup fail:

What print() hides and repr() shows Python · print_values.py
prices = {"tea": 30, "coffee": 60}
item = "coffee "  # read from a file, with a space at the end
print(item)
print(repr(item), type(item))
print(item in prices)

Output

coffee 
'coffee ' <class 'str'>
False

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 print_values.py

And here is step 3 on bill.py: the two lines that still raise the same error make a The smallest program that still shows a bug, made by deleting everything the error does not need. Making one often finds the bug; if not, it is what you show when you ask for help.:

bill.py shrunk to two lines Python · minimal.py
prices = {"coffee": 60}
print(prices["cofee"])

Output (exit status 1)

Printed as an error (standard error)

Traceback (most recent call last):
  File "minimal.py", line 2, in <module>
    print(prices["cofee"])
          ~~~~~~^^^^^^^^^
KeyError: 'cofee'

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 minimal.py

Security

Before you paste code or a traceback into a forum or an AI assistant, take out passwords, API keys, tokens and personal data. Tracebacks contain file paths, which often include your user name, and the code around each failing line.

Python Online Compiler Run bill.py in your browser, select a line of its traceback to jump to that line, and fix the order.

Checkpoint

Check: Getting unstuck

  1. One question print(repr(item), type(item)) shows 'coffee ' <class 'str'>, and prices[item] raises KeyError although prices has a key "coffee". Why?

    Choose one answer.

    Show the answer: One question

    Answer: The value ends with a space, so it is a different key from "coffee"

    repr() shows a value as you would write it in code, quotes and spaces included, so 'coffee ' gives the trailing space away. print(item) would have shown coffee followed by an invisible space.

Practise: fix a bill by reading its tracebacks

bill_total() adds up an order written as lines of text, and its starter code fails with two different tracebacks. Run the sample tests, read each traceback from the bottom up, and fix each bad value where it comes from:

Exercise · Easy · Python

Fix a bill by reading its tracebacks

bill_total(lines) adds up an order given as lines of text, each an item and a quantity separated by a comma, such as "tea,2", with the prices in PRICES:

  • bill_total(["tea,2", "toast,1"]) returns 105.
  • Spaces around the item or the quantity are allowed: bill_total([" coffee , 2"]) returns 120.
  • An empty order returns 0.

The starter code is almost right, and it fails. Run the sample tests and read each traceback from the bottom up: the last line names the error, the frame above it shows the line that failed, and the bad value came from somewhere before that line. Fix each value where it comes from, then run the tests again.

Starter code · bill.py

PRICES = {"tea": 30, "toast": 45, "coffee": 60}


def bill_total(lines):
    """Add up an order given as lines of text such as "tea,2"."""
    total = 0
    for line in lines:
        item, quantity = line.split(",")
        total += PRICES[item] * quantity
    return total
The sample tests · test_bill.py
from bill import bill_total


def test_two_lines():
    """adds up each item's price times its quantity"""
    assert bill_total(["tea,2", "toast,1"]) == 105


def test_spaces():
    """allows spaces around the item and the quantity"""
    assert bill_total([" coffee , 2"]) == 120
    assert bill_total(["tea , 1", " toast,2 "]) == 120


def test_empty_order():
    """an empty order costs nothing"""
    assert bill_total([]) == 0
A hint

The first traceback ends with TypeError: unsupported operand type(s) for +=: 'int' and 'str' on the line with +=. One of the two sides is text: add print(repr(quantity)) above that line and run the tests again. int() turns text such as " 2 " into a number, spaces and all. The next traceback names a key with spaces in it, and .strip() removes spaces from both ends of a string.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then work through the questions on all five ideas, from reading frames to getting unstuck. An idea you miss is asked about again first, and every pick tells you what it got right or wrong:

Practice that adapts to you

Practise this lesson

14 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 14 What does "most recent call last" at the top of a traceback mean?

    Choose one answer.

    Show the answer: Question 1 of 14

    Answer: The frames run from the first call down to the line that failed, which comes last

    Python prints the calls in the order they were made, so the most recent one, the line that failed, is last, just above the exception. That is why you read a traceback from the bottom up.

  2. Question 2 of 14 What does bill.py print on standard output before its traceback?

    What does this program print? Choose one answer.

    prices = {"tea": 30, "toast": 45, "coffee": 60}
    
    
    def line_total(item, quantity):
        return prices[item] * quantity
    
    
    def bill(order):
        total = 0
        for item, quantity in order:
            total += line_total(item, quantity)
        return total
    
    
    print("First bill:", bill([("tea", 2), ("toast", 1)]))
    print("Second bill:", bill([("tea", 1), ("cofee", 2)]))
    Show the answer: Question 2 of 14

    Answer: it prints

    First bill: 105

    Line 15 prints the first bill, 105, before line 16 starts the second bill, whose lookup fails. The traceback goes to standard error.

  3. Question 3 of 14 The last four frames of a traceback are in …/lib/python3.14/json/decoder.py and __init__.py. Where do you look first?

    Choose one answer.

    Show the answer: Question 3 of 14

    Answer: At the last frame in your own file, the line that called json.loads(), and at what it passed in

    When the last frames are in someone else's code, find the last frame in your own file: that line called the library, and what it passed in is usually what is wrong, as with the single quotes in bad_json.py.

  4. Question 4 of 14 An IndentationError stops a file. What kind of error is it, and when does Python report it?

    Choose one answer.

    Show the answer: Question 4 of 14

    Answer: A kind of SyntaxError, reported before anything in the file runs

    IndentationError is a subclass of SyntaxError. Like every grammar mistake it is found while Python compiles the whole file, so nothing runs.

  5. Question 5 of 14 Why does the report of a SyntaxError have no "Traceback (most recent call last)" line?

    Choose one answer.

    Show the answer: Question 5 of 14

    Answer: No call happened, because the file never started running

    The chain of calls is what "Traceback (most recent call last)" introduces. A file that cannot be compiled never runs, so the report shows only the file, the line, a mark and the message.

  6. Question 6 of 14 Which exception does "3" + 4 raise?

    Choose one answer.

    Show the answer: Question 6 of 14

    Answer: TypeError

    The message says it: can only concatenate str (not "int") to str. Decide which you meant, int("3") + 4 or "3" + str(4).

  7. Question 7 of 14 average = sum(marks) / len(marks) raises ZeroDivisionError. What do you check first?

    Choose one answer.

    Show the answer: Question 7 of 14

    Answer: Whether marks can be empty, because then len(marks) is 0

    Look at what can be 0 in the divisor. Counts and lengths are the usual suspects: an empty list has no average, and the code has to decide what to do when there are no marks.

  8. Question 8 of 14 A script saved as json.py stops with AttributeError: module 'json' has no attribute 'loads' and a hint to consider renaming it. What is the fix?

    Choose one answer.

    Show the answer: Question 8 of 14

    Answer: Rename the file, for example to settings_check.py, so that import json finds the standard library's module

    A file named after a module you import shadows that module. Python 3.13 and newer say so in the message: rename the file, and import json finds the standard library again.

  9. Question 9 of 14 Since which Python version do the ~ and ^ marks point at the exact part of a line that failed?

    Choose one answer.

    Show the answer: Question 9 of 14

    Answer: 3.11

    Python 3.11 added the ~ and ^ marks (PEP 657), which pick out the part of a long line that failed, such as the lookup prices[item] in bill.py.

  10. Question 10 of 14 What does Python 3.13 print for stock[["tea", "toast"]] = 2?

    Choose one answer.

    Show the answer: Question 10 of 14

    Answer: TypeError: unhashable type: 'list'

    Both versions refuse a list as a dict key with TypeError. Python 3.14 adds what you were doing, cannot use 'list' as a dict key, to the older unhashable type: 'list'.

  11. Question 11 of 14 In the shell, which call shows the documentation of the built-in function len?

    Choose one answer.

    Show the answer: Question 11 of 14

    Answer: help(len)

    help(len) prints the documentation of len, its signature and what it returns. issubclass(KeyError, LookupError) tells you which broader kind of error an exception belongs to.

  12. Question 12 of 14 What is a minimal example?

    Choose one answer.

    Show the answer: Question 12 of 14

    Answer: The smallest program that still shows the error, made by deleting what the error does not need

    Copy the program and delete everything that is not needed to make the error happen, until only a few lines are left, as minimal.py does for the KeyError of bill.py.

  13. Question 13 of 14 Before you paste code and a traceback into a forum or an assistant, what should you take out?

    Choose every answer that is right.

    Show the answer: Question 13 of 14

    Answer:

    • Your user name in the file paths
    • Passwords, API keys and tokens
    • Personal data, such as names and addresses in the data

    Keep the exception, its message and the lines that matter; take out secrets, personal data and the parts of paths that say who you are.

  14. Question 14 of 14 Your program stops with KeyError: 'cofee' in your own function line_total. Which search is most likely to find help?

    Choose one answer.

    Show the answer: Question 14 of 14

    Answer: Python KeyError dictionary lookup, without cofee and line_total

    Search for the last line, leaving out the names and values that are particular to your program, and add what the code was doing, such as a dictionary lookup.

Interview questions

Warm-up (fresher): how do you read a Python traceback?

From the bottom up. The last line names the exception and its message, such as KeyError: 'cofee', which says what went wrong. The frame above it gives the file, the line number and the function where it happened, with the line itself and marks under the part that failed. The frames higher up are the calls that led there, oldest first, which is what “most recent call last” means. The line that failed is not always the line to fix: follow the bad value up the frames to where it came from, and skip frames inside libraries to the last one in your own code. A SyntaxError report has no chain of calls, because the file never started running.

Two harder questions start from this lesson: an error raised deep inside a library, and one mistake that two Python versions describe differently. Find your first step before you open each one:

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A nightly job stops with KeyError: 'cofee'. The last three frames of its traceback are inside a pricing library you installed; your own code appears higher up. A teammate wants to wrap the library call in try/except KeyError and use a price of 0. What do you do instead, and why?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    A teammate saved the dice script as random.py. With Python 3.14 the error says to consider renaming random.py; on a server with Python 3.12 the same file reports a partially initialized module, most likely a circular import. Explain what really happens in both cases, and how you would stop it happening again.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Read a traceback from the bottom: the exception and its message, then the line that failed, then the calls above it.
  • The bug is often higher up than the failing line: follow the bad value back to where it came from, and skip the frames inside libraries.
  • A SyntaxError means nothing ran; when the line shown looks fine, look for an unclosed bracket or quote before it.
  • Python 3.14 suggests misspelt keywords and explains unhashable keys; Did you mean …? hints for names and attributes are older.
  • Get unstuck with the documentation and help(), a print() of the values involved, and a minimal example, and never paste secrets into a question.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.