Chapter 1 · Foundations
Reading errors and tracebacks
Step 1 of 21 · Concept
Everyone gets errors
By the end of this lesson you can read what Python says when a program is wrong, and fix it.
Everyone writes programs with mistakes. Python's messages look strange at first, but they say what is wrong and where.
In this lesson you will:
- tell the two kinds of error apart,
- fix syntax errors one at a time,
- read a traceback when a program crashes.
Step 2 of 21 · Concept
Two kinds of error
| kind | what stops | what you see |
|---|---|---|
| syntax error | Python cannot read the file you run | no output, only the error |
| exception | a line fails while the program runs | the output so far, then the error |
Step 3 of 21 · Quiz
Did it run?
You press Run on this program. What does it print before the error?
print("Start")
print("Middle")
print("End"
Step 4 of 21 · Demo
A missing bracket
Run it: nothing is printed. Read the last line of the message, SyntaxError: '(' was never closed.
Step 5 of 21 · Concept
Read the message from the bottom
Read the last line first: SyntaxError, then what is wrong. Then go to the top:
File "...", line 3: the file and the line it is on,- the line itself, as you wrote it,
- a caret,
^, under the place where Python noticed.
Run shows the whole path, /home/student/05-errors/paren/main.py. This course writes it main.py.
Step 6 of 21 · Concept
Where the caret points
The caret marks where Python noticed the problem. That is not always where the mistake is.
- An unclosed bracket is blamed where it opened: under the
(ofprint("End". - A missing
"givesunterminated string literal (detected at line 1): the text runs on to the end of the line.
Step 7 of 21 · Quiz
What does Python mean?
Python stops with this message. What is wrong?
File "main.py", line 1
print("Hello)
^
SyntaxError: unterminated string literal (detected at line 1)
Step 8 of 21 · Concept
One error at a time
print("one"
print("two)
Python stops with one message:
File "main.py", line 2
print("two)
^
SyntaxError: unterminated string literal (detected at line 2)
- Python reports one syntax error per run, and not always the topmost.
- A missing
"is found when Python reads that line. An unclosed(is found only at the end of the file. - Fix the error it names, then run again.
Step 9 of 21 · Exercise
Your turn: two mistakes
This program has two mistakes. Fix the one Python names, run again, and repeat. Then add a third line, so that it prints:
Ready
Set
Go!
Python names line 2 first: unterminated string literal (detected at line 2). The mistake on line 1 waits for the next run.
Line 2 needs a " before its ). Run again: now Python says '(' was never closed and names line 1.
A ( needs its ). The new line is one more print, with its text in quotes.
Step 10 of 21 · Concept
Exceptions stop the program
An exception stops a program while it runs. Its name says what kind of problem it is:
| exception | a typical cause |
|---|---|
NameError | a name Python does not know: prnt("Hi") |
TypeError | text and a number joined: "Age: " + 15 |
ValueError | text that is not a number: int("abc") |
ZeroDivisionError | dividing by 0, with /, // or % |
The program A crash in the middle has two functions, like lesson 2's greet. share(10, 0) runs share with
total 10 and people 0. return gives back its answer (lesson 7).
Step 11 of 21 · Demo
A crash in the middle
Run it. Sharing... prints, then the program crashes. Read the traceback's last line.
Step 12 of 21 · Concept
A traceback is the stack
When it crashed, share was running, called by main, called from the <module> frame. A traceback lists
those frames:
Traceback (most recent call last):, then aFile "...", line N, in ...line per frame,- the
<module>frame first, the frame that failed last, - then the error,
ZeroDivisionError: division by zero.
Read the last line first, then the File line before it.
Step 13 of 21 · Quiz
Who passed the 0?
The program stopped with this traceback. share divides by people, and people was 0. Which line gave it that
0?
Traceback (most recent call last):
File "main.py", line 10, in <module>
main()
~~~~^^
File "main.py", line 7, in main
print(share(10, 0))
~~~~~^^^^^^^
File "main.py", line 2, in share
return total // people
~~~~~~^^~~~~~~~
ZeroDivisionError: division by zero
def share(total, people):
return total // people
def main():
print("Sharing...")
print(share(10, 0))
main()Step 14 of 21 · Try it
Try it: blame the caller
It should print Ada: 90, then Bob: 0, but it crashes. Read the traceback, go to the line of main it names, and
fix the call there. percent itself is right.
percent takes the points first, then the total. Compare Bob's call with Ada's, which works.
Step 15 of 21 · Concept
Text and numbers do not mix
You met this one in lesson 4:
age = 15
print("Age: " + age)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Age: " + age)
~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str
The ^ sits under the +: it cannot join, or concatenate, a str and an int. Fix it with str(age), or
with an f-string: f"Age: {age}".
Step 16 of 21 · Quiz
A value that does not fit
This program stops with a traceback. What is wrong?
text = "abc"
n = int(text)
Traceback (most recent call last):
File "main.py", line 2, in <module>
n = int(text)
ValueError: invalid literal for int() with base 10: 'abc'
Step 17 of 21 · Concept
A misspelt name
A NameError means Python knows no such name. Often it guesses what you meant:
NameError: name 'prnt' is not defined. Did you mean: 'print'?
The guess is a guess, and it is not always there. For nmae, two letters swapped, Python gives none:
NameError: name 'nmae' is not defined
Capitals count too: Print is not print (lesson 1).
Step 18 of 21 · Quiz
Which fix?
This program stops with a NameError. Which fix makes it print Hello, Ada?
name = "Ada"
print("Hello, " + nmae)
NameError: name 'nmae' is not defined
Step 19 of 21 · Check yourself
Check yourself: pizza for everyone
This program has three mistakes. Python finds one before any line runs, and two while it runs. Fix them one run at a time, so that it prints exactly:
Pizzas: 3
Slices each: 6
Enjoy!
Run it, read the last line of the message, fix that one mistake, and run again. Three runs, three fixes.
Step 20 of 21 · Challenge · optional
Challenge: your own message
Optional.
share checks people first. The line under if people < 1: runs only when people is less than 1 (lesson 6
teaches if). Make the program stop there with a ValueError and your own message, so that the traceback's last
line is:
ValueError: people must be more than 0
Run it: the message prints, and then // still divides by 0. The program must stop at the message instead.
raise stops the program with an exception you make: raise ValueError("...") makes a ValueError with your text (lesson 17 explains it). It takes the place of the print, at the same indent.
raise ValueError("...")
Step 21 of 21 · Recap
Recap
- A syntax error stops Python before any line runs; an exception stops it in the middle.
- Read a message from its last line, then the file and the line.
- One syntax error per run: fix it, then run again.
- A traceback lists the stack,
<module>first. The fix is often in the caller. - The exit code is 1 after an error, 0 after a good run.
Next: lesson 6 makes programs decide and repeat, and meets IndentationError.
Review
5 questions from this lesson, in a new order each time. Answer from memory: 3 of 5 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
print("Start")
print("Middle")
print("End"
print("Ready"
print("Set)
def share(total, people):
return total // people
def main():
print("Sharing...")
print(share(10, 0))
main()
def percent(points, total):
return points * 100 // total
def main():
total = 20
ada = 18
bob = 0
print("Ada:", percent(ada, total))
print("Bob:", percent(total, bob))
main()
pizzas = 3
guests = 4
slices = pizzas * 8
print("Pizzas: " + pizzas)
print("Slices each:", slices // gests)
print("Enjoy!"
def share(total, people):
if people < 1:
print("people must be more than 0")
return total // people
print("Sweets each:", share(12, 4))
print("Sweets each:", share(12, 0))