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.
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Start at the last line and work upwards:
- 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. - 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 lookupprices[item]. - Each frame higher up is a call that led there.
bill()calledline_total()on line 11, and the file’s top level (<module>) calledbill()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:
The drawing shows the whole scene; its 8 steps are listed below.
Every step as text
- 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.
- 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.
- 30 comes back. line_total() returns 30, one tea at 30, and bill() adds it to the total.
- The second item. Line 11 runs again, now for the second item of the order.
- 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.
- 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.
- 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.
- 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:
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"}'.
Checkpoint
Check: Reading a traceback from the bottom up
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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:
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
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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:
- 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.
- 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.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.
- 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 …?
- 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
When you are stuck, read, print, shrink, then search
-
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, andissubclass()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) TrueThis session was replayed with Python 3.14.8 on macOS 26 arm64, and it printed exactly what is shown.
-
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. -
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.
-
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:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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.:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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.
Checkpoint
Check: Getting unstuck
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"])returns105.- Spaces around the item or the quantity are allowed:
bill_total([" coffee , 2"])returns120. - 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.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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.
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.
-
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?
-
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.
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
SyntaxErrormeans 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(), aprint()of the values involved, and a minimal example, and never paste secrets into a question.
References
- The Python Tutorial: Errors and Exceptions (Python Software Foundation)
- Built-in Exceptions (Python Software Foundation)
- What's New In Python 3.14: improved error messages (Python Software Foundation)
- What's New In Python 3.13: improved error messages (Python Software Foundation)
- What's New In Python 3.12: improved error messages (Python Software Foundation)
- What's New In Python 3.10: better error messages (Python Software Foundation)
- PEP 657: Include fine-grained error locations in tracebacks (Python Software Foundation)
- traceback, print or retrieve a stack traceback (Python Software Foundation)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress