How to read an error message
Python's error messages look scary but they are helpful. Read from the bottom: the last line names the error, and the line above shows where Python got stuck. The real mistake is often on that line or the one just before it.
IndentationError
Code inside an if, loop or function must be indented by four spaces.
Wrong
if age >= 18:
print("You can vote")Right
if age >= 18:
print("You can vote")Parent tip: think of indentation like paragraphs. Everything that belongs together lines up.
NameError
You used a variable before creating it, or spelled it differently. Score and score are different names.
Wrong
print(score)
score = 100Right
score = 100
print(score)TypeError
You tried to combine different types, such as text and a number. input() always gives text.
Wrong
age = input("Age: ")
print(age + 1)Right
age = int(input("Age: "))
print(age + 1)IndexError
You asked for a position that does not exist. Lists start at 0, so a list of three items has positions 0, 1 and 2.
Wrong
pets = ["cat", "dog", "fish"]
print(pets[3])Right
pets = ["cat", "dog", "fish"]
print(pets[2])SyntaxError
Python cannot understand the line. Check for a missing colon, bracket or quotation mark.
Wrong
if score > 10
print("Well done")Right
if score > 10:
print("Well done")ValueError
The type is right but the value cannot be converted, for example int("ten"). Check what the user typed, or use validation.
Logic errors
The program runs but gives the wrong answer. Python cannot spot these for you. Use a trace table or add print() lines to see what each variable holds.
Wrong (prints 1 to 9)
for i in range(1, 10):
print(i)Right (prints 1 to 10)
for i in range(1, 11):
print(i)
