An Introduction to Programming

Python for All

Chapter Twelve — Understanding Errors

Thanasis Troboukis  ·  All Chapters

Chapter Twelve

Understanding Errors

When Python stops and shows an error message, it is giving you information. Learning to read that message is one of the most useful skills a programmer can have.

Reading an Error Message

When Python cannot run your code, it prints a traceback. A traceback is a report that tells you where the problem is and what went wrong. Run this cell to see a real one.

Python · Run this — it will produce an error

      

You will see something like this:

Traceback (most recent call last):
  File "<string>", line 2, in <module>
    print(nane)
NameError: name 'nane' is not defined

Here is how to read it:

Part of the message What it means
line 2 The problem is on line 2 of your code.
print(nane) This is the exact line that caused the error.
NameError: name 'nane' is not defined The error type and a short explanation of what went wrong.
Always read the last line first. It names the error type and tells you what Python could not do. Then look up one line to see which line of code triggered it.

SyntaxError — Python Cannot Understand the Code

Python reads your entire program before it runs a single line. If it finds something it cannot parse — a missing colon, an unclosed parenthesis, an unclosed string — it stops immediately with a SyntaxError.

Common causes:

Python · Run this — missing colon after if

      

The error points to line 2 and says invalid syntax. The fix is to add the missing colon after if age > 18.

Python · Fixed version

      
Nothing runs when there is a SyntaxError. Because Python reads the whole file first, even lines that appear before the broken one will not execute. Fix the syntax and run again.

NameError — Python Does Not Know That Name

A NameError means you used a name — a variable, a function, anything — that Python has never seen before in your program. The two most common causes are a typo in the name and using a variable before you have defined it.

Python · Run this — typo in variable name

      

The message says name 'citty' is not defined. Python tells you the exact name it could not find. Comparing citty to your code reveals the typo instantly.

Python · Run this — variable used before it is defined

      

Python runs code from top to bottom. When it reaches line 1, score does not exist yet. Moving the assignment above the print fixes it.

Python · Fixed version

      

TypeError — Wrong Type for the Operation

A TypeError means the operation makes sense in general, but the types you gave it do not match. The classic example is trying to join a number and a string with +.

Python · Run this — adding a number to a string

      

The message says something like can only concatenate str (not "int") to str. Python knows how to join two strings, but not a string and an integer. Convert the number first with str().

Python · Fixed version — convert the number to a string

      

TypeErrors also appear when you call something that is not a function, or when you pass the wrong number of arguments to a function.

Python · Run this — calling a value that is not a function

      

number holds an integer, not a function. You cannot call an integer with ().

f-strings avoid the string + number problem entirely. f"My age is {age}" handles the conversion automatically, so you never need to write str(age) inside an f-string.

ValueError — Right Type, Wrong Value

A ValueError happens when the type is correct but the value does not make sense for the operation. The most common example is trying to convert a word to a number.

Python · Run this — converting a word to an integer

      

The message says invalid literal for int() with base 10: 'hello'. int() can convert "42" to 42, but it cannot make sense of a word. The value needs to actually look like a number.

Python · This works — the string contains a valid number

      
Remember: int() needs a string that looks like a whole number. float() is more flexible — float("3.14") works — but neither can parse a word.

IndexError and KeyError — Looking Up Something That Is Not There

These two errors both happen when you ask for something that does not exist: a position in a list that is too large, or a key in a dictionary that was never added.

IndexError

A list with three items has positions 0, 1, and 2. Asking for position 3 or beyond raises an IndexError.

Python · Run this — index out of range

      

The message says list index out of range. The list only goes up to index 2. Use len(fruits) if you are unsure how many items a list contains — the last valid index is always len(fruits) - 1.

KeyError

A KeyError happens when you ask a dictionary for a key that does not exist in it.

Python · Run this — key not in dictionary

      

The message shows KeyError: 'email'. The dictionary has no "email" key. You can check before accessing with if "email" in person:, or use .get() which returns None instead of raising an error.

Python · Safe lookup with .get()

      
Quick reference — the errors you now know:
SyntaxError — Python cannot parse the code.
NameError — a name was never defined.
TypeError — the types do not match the operation.
ValueError — the type is right but the value makes no sense.
IndexError — list position does not exist.
KeyError — dictionary key does not exist.

Your Turn

Each cell below contains broken code. Run it, read the error message, figure out what is wrong, and fix it.

Python · Exercise 1 — fix the error

      
Python · Exercise 2 — fix the error

      
Python · Exercise 3 — fix the error

      
Python · Exercise 4 — fix the error

      
Congratulations — you have completed Book 1. You now know variables, strings, lists, dictionaries, booleans, functions, regex basics, file handling, and how to read error messages. That is a strong base for everything that comes next.

Chapter Navigation

Move between chapters.

Loading Python environment — this may take a moment…