print()A bug is a mistake in a program. Every programmer, beginner or expert, writes bugs every day. What separates beginners from experienced programmers is not fewer bugs. It is knowing what to do next.
Bugs come in two kinds. Some stop the program with an error message. Those are the friendly ones, because Python tells you what went wrong and where. Others run without any error but give the wrong answer. Those take a little detective work, and you will learn that too.
The habit to build today: when you see red text, don't panic and don't guess. Read it.
Here is a program with a typo, and what Python says when you run it:
score = 5
print(scroe)
Traceback (most recent call last):
File "C:\python-course\bug1.py", line 2, in <module>
print(scroe)
^^^^^
NameError: name 'scroe' is not defined. Did you mean: 'score'?
That looks like a lot, but you only need two parts, and you read them from the bottom up:
NameError is the kind of error, and the rest explains it: Python has never heard of a name called scroe.line 2 tells you which line of your file, and the line of code is shown right under it.Start at the bottom, then find the line number. Everything else in the message can be ignored for now. Your message may look slightly different from this one, because the underline marks and the "Did you mean" hint depend on your version of Python. The last line and the line number are always there.
A SyntaxError means the code is broken like a sentence with a missing word. The usual causes are a missing colon, a missing closing quote or parenthesis, or a mix-up between = and ==.
age = 12
if age >= 10
print("Old enough")
File "bug.py", line 2
if age >= 10
^
SyntaxError: expected ':'
Every if, elif, else, for and while line ends with a colon. Add it and the error is gone.
An unclosed parenthesis looks like this:
print("Hello"
print("World")
File "bug.py", line 1
print("Hello"
^
SyntaxError: '(' was never closed
And here is the classic mix-up from the Booleans lesson, = where you meant ==:
age = 12
if age = 12:
print("Twelve")
File "bug.py", line 2
if age = 12:
^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
In Python this is an error, not a silent bug, so Python stops you. Use == to ask a question.
Tip: Python reads the whole file before running any of it, so a SyntaxError appears before anything prints. If the line it points to looks fine, check the line above it. The real mistake is often just before.
age = 12
if age >= 10:
print("Old enough")
File "bug.py", line 3
print("Old enough")
^
IndentationError: expected an indented block after 'if' statement on line 2
The line after a colon must be indented, usually four spaces. Indent it and run again.
print(Hello)
NameError: name 'Hello' is not defined
Three causes cover almost every NameError: a typo in a variable name (scroe for score), forgetting the quotes around text (Hello instead of "Hello"), or using a name before you created it. Capital letters count, so true instead of True gives this error too.
print("Age: " + 12)
TypeError: can only concatenate str (not "int") to str
You tried to join text and a number with +. Show them with a comma instead, print("Age:", 12), or convert the number with str(). This is also what you get when you forget int() on an answer from input().
fruits = ["apple", "banana", "cherry"]
print(fruits[3])
IndexError: list index out of range
The list has three items, at positions 0, 1 and 2. There is no position 3. Remember that counting starts at 0, so the last position is one less than len().
student = {"name": "Mia"}
print(student["age"])
KeyError: 'age'
The dictionary has no entry labeled age. Check your spelling, and check that the entry was added before you read it.
age = int("twelve")
ValueError: invalid literal for int() with base 10: 'twelve'
int() can only convert text that looks like a whole number. twelve and 12.5 both fail.
| Error | It usually means | Check first |
|---|---|---|
SyntaxError |
Python can't read the code | Colon, quotes, parentheses, = vs == |
IndentationError |
Spaces are wrong | Indent the line after a colon |
NameError |
Python doesn't know the name | Typos, missing quotes, capital letters |
TypeError |
Wrong kinds of things together | Text plus a number |
IndexError |
List position doesn't exist | Counting from 0, len() |
KeyError |
Dictionary label doesn't exist | Spelling of the key |
ValueError |
Right type, wrong value | Does the text look like a number? |
You will meet others, such as ZeroDivisionError when you divide by zero (10 / 0). The method for handling them is exactly the same.
The fourth step matters most. If you change five things at once and the bug disappears, you won't know why, and if it gets worse, you won't know which change did it.
The hardest bugs run perfectly and give the wrong answer. Python can't warn you, because it did exactly what you asked. It just wasn't what you meant.
a = 10
b = 20
average = a + b / 2
print(average)
20.0
You expected 15.0, the average of 10 and 20, and got 20.0. There is no error to read, so you have to look inside the program.
print() is your flashlight. Add a line that shows what a value actually is, run the program, and compare it with what you expected:
total = 0
for number in range(1, 4):
total = total + number
print("number is", number, "total is", total)
print(total)
number is 1 total is 1
number is 2 total is 3
number is 3 total is 6
6
Each line shows the program's thinking at that moment. When a value is not what you expected, you have found where the bug starts. For the average bug, the cause is the order of operations from the Numbers lesson: division happens before addition, so b / 2 ran first. Parentheses fix it:
average = (a + b) / 2
Once the bug is fixed, delete the extra print() lines.
15.0 but prints 20.0. Find the bug and fix it:a = 10
b = 20
average = a + b / 2
print(average)
print() lines inside its loop to show the values at each step. Then remove them.Save this as lesson14-practice.py and run it with F5 in IDLE. On a Mac, if F5 does nothing, use Run, then Run Module, from the menu.
scores = [80, 95, 70]
total = 0
for score in scores
total = total + score
print("Total:", totl)
average = total / len(scores)
print("Average: " + average)
SyntaxError, IndentationError, NameError, TypeError, IndexError, KeyError and ValueError.print() to look inside it.Next lesson: Functions: Reusable Blocks.
Work through the slides with Helio's narration, or download them:
Open the slidesDownload PowerPointDownload PDF
# Lesson 14: Debugging practice: three bugs
# WHAT TO DO: This program should add up three scores and print their
# total and average. It has three bugs, one at a time. Run it, read the
# error message from the bottom up, fix that one bug, then run it again.
# Each fix reveals the next bug.
# HINT: the bugs are a SyntaxError, a NameError, and a TypeError.
# Run with F5 in IDLE. You are done when it prints exactly:
# Total: 245
# Average: 81.66666666666667
scores = [80, 95, 70]
total = 0
for score in scores
total = total + score
print("Total:", totl)
average = total / len(scores)
print("Average: " + average)
Save the file as lesson14-practice.py and run it with F5 in IDLE. On a Mac, if F5 does nothing, use Run, then Run Module, from the menu.
Five quick questions on this lesson. Take the Lesson 14 quiz
Enroll free in the full course — same 17 lessons, with your progress saved. Free, no payment.