Skip to main content
Editor

How to Read Python Error Messages and Fix Common Bugs

Beginner20 min6 exercises75 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/6 exercises

When beginners see a red error message, their first instinct is panic. The screen fills with scary-looking text, and they think they broke something badly. But here's the truth: error messages are your best friend. They tell you exactly what went wrong and where.

Professional programmers see errors every single day. The difference between a beginner and an expert isn't that experts avoid errors - it's that experts know how to read them. Once you learn to read Python's error messages, debugging goes from terrifying to almost automatic.

In this tutorial, you'll learn how to read a Python traceback, understand the six most common error types, and build a mental toolkit for fixing bugs quickly.

How to Read a Python Traceback

When Python hits an error, it prints a traceback - a report that tells you what happened. Most people read tracebacks from top to bottom. That's backwards. Always start reading from the last line.

Code that produces a traceback
def greet(name):
message = 'Hello, ' + name
return message
result = greet(42)
Output
Traceback (most recent call last):
  File "<exec>", line 5, in <module>
  File "<exec>", line 2, in greet
TypeError: can only concatenate str (not "int") to str

When you run this code, Python shows a traceback. Here's how to read it, starting from the bottom:


SyntaxError: Python Can't Understand Your Code

A SyntaxError means Python can't even begin to run your code because the structure is wrong. It's like a grammar error in English - the sentence doesn't make sense. Python catches these before running a single line.

Common SyntaxError causes
# Missing colon after if
try:
exec('if True\n print("hello")')
except SyntaxError as e:
print(f'SyntaxError: {e}')
# These are the most common causes:
print('Common SyntaxError causes:')
print('1. Missing colon after if/else/for/while/def')
print('2. Mismatched parentheses or quotes')
print('3. Using = instead of == in conditions')
print('4. Incorrect indentation')
Output
SyntaxError: expected ':' (<string>, line 1)
Common SyntaxError causes:
1. Missing colon after if/else/for/while/def
2. Mismatched parentheses or quotes
3. Using = instead of == in conditions
4. Incorrect indentation

The good news: SyntaxErrors are usually the easiest to fix. Python often points right at the problem with a little arrow (^) showing where it got confused.

Broken: missing colon
if temperature > 30
    print('Hot!')
Fixed: added the colon
if temperature > 30:
    print('Hot!')

NameError: Python Can't Find That Name

A NameError means you used a variable or function name that Python doesn't recognize. This usually means you have a typo, forgot to define the variable, or used it before assigning a value.

Common NameError examples
# Typo in variable name
username = 'Alice'
try:
print(usernme) # Oops - misspelled!
except NameError as e:
print(f'NameError: {e}')
# Using a variable before defining it
try:
print(score)
score = 100
except NameError as e:
print(f'NameError: {e}')
Output
NameError: name 'usernme' is not defined
NameError: name 'score' is not defined
Bug: variable name typo
total_price = 49.99
print(total_prce)  # typo!
Fixed: correct spelling
total_price = 49.99
print(total_price)

TypeError: Wrong Type for the Operation

A TypeError means you tried to do something with the wrong type of data. Like trying to add a string and a number, or calling something that isn't a function. Python knows what you asked for, but the types don't match.

Common TypeError examples
# Can't add string and integer
try:
result = 'Age: ' + 25
except TypeError as e:
print(f'TypeError: {e}')
# Can't multiply string by string
try:
result = 'hello' * 'world'
except TypeError as e:
print(f'TypeError: {e}')
# Wrong number of arguments
def add(a, b):
return a + b
try:
add(1, 2, 3)
except TypeError as e:
print(f'TypeError: {e}')
Output
TypeError: can only concatenate str (not "int") to str
TypeError: can't multiply sequence by non-int of type 'str'
TypeError: add() takes 2 positional arguments but 3 were given

TypeErrors often pop up when working with user input (which is always a string) or when a function returns None unexpectedly.

Bug: mixing string and int
age = 25
print('You are ' + age + ' years old')
Fixed: use f-string or str()
age = 25
print(f'You are {age} years old')

IndexError and KeyError: Accessing Things That Don't Exist

An IndexError happens when you try to access a list position that doesn't exist. A KeyError happens when you try to access a dictionary key that doesn't exist. Both mean you're reaching for something that isn't there.

IndexError and KeyError examples
# IndexError - list index out of range
fruits = ['apple', 'banana', 'cherry']
try:
print(fruits[5]) # Only indices 0, 1, 2 exist!
except IndexError as e:
print(f'IndexError: {e}')
print(f'List length: {len(fruits)}')
print(f'Valid indices: 0 to {len(fruits) - 1}')
# KeyError - dictionary key doesn't exist
user = {'name': 'Alice', 'age': 25}
try:
print(user['email']) # This key doesn't exist!
except KeyError as e:
print(f'KeyError: {e}')
Output
IndexError: list index out of range
List length: 3
Valid indices: 0 to 2
KeyError: 'email'

For dictionaries, you can avoid KeyError by using the .get() method, which returns a default value instead of crashing.

Crashes with KeyError
user = {'name': 'Alice'}
email = user['email']  # KeyError!
Safe with .get()
user = {'name': 'Alice'}
email = user.get('email', 'Not provided')
print(email)  # Not provided

ValueError: Right Type, Wrong Value

A ValueError means the type is correct but the actual value doesn't make sense for the operation. The classic example: trying to convert a non-numeric string to an integer.

Common ValueError examples
# Can't convert "hello" to an integer
try:
number = int('hello')
except ValueError as e:
print(f'ValueError: {e}')
# Can't convert a decimal string with int()
try:
number = int('3.14')
except ValueError as e:
print(f'ValueError: {e}')
# This works - go through float first
number = int(float('3.14'))
print(f'Converted: {number}')
Output
ValueError: invalid literal for int() with base 10: 'hello'
ValueError: invalid literal for int() with base 10: '3.14'
Converted: 3

ValueErrors come up frequently when processing user input. A user might type "twenty" instead of "20", or leave a field blank. Always validate input before converting it.

Handling ValueError with try/except
# Safe conversion pattern
user_input = 'abc'
try:
age = int(user_input)
print(f'Your age is {age}')
except ValueError:
print(f'\"{user_input}\" is not a valid number')
Output
"abc" is not a valid number

Common Debugging Tips

Here's a quick-reference guide for debugging Python code. These techniques work for every error type.

Here's a quick reference of the errors you'll encounter most often:

ErrorWhat It MeansQuick Fix
SyntaxErrorCode structure is wrongCheck colons, parentheses, quotes
NameErrorVariable/function not foundCheck spelling, define before use
TypeErrorWrong data typeConvert types or check function args
IndexErrorList index out of rangeCheck list length, use 0-based indexing
KeyErrorDict key not foundUse .get() or check key exists
ValueErrorRight type, wrong valueValidate data before converting

Practice Exercises

Time to practice your debugging skills! Most of these exercises give you broken code to fix. Read the error message, find the bug, and repair it.

Exercise 1: Fix the SyntaxError
Fix the Bug

This code has a SyntaxError. Find and fix it so it prints:

Python is fun!
Let's learn more.
message = 'Python is fun!'
print(message
print('Let\'s learn more.')
Exercise 2: Fix the NameError
Fix the Bug

This code has a NameError. Find the typo and fix it so it prints:

Hello, Alice! You have 3 new messages.
user_name = 'Alice'
message_count = 3
print(f'Hello, {user_name}! You have {mesage_count} new messages.')
Exercise 3: Fix the TypeError
Fix the Bug

This code has a TypeError. Fix it so it prints:

Your total is $37.5
price = 12.5
quantity = '3'
total = price * quantity
print(f'Your total is ${total}')
Exercise 4: Fix the IndexError
Fix the Bug

This code tries to print the last color but crashes with an IndexError. Fix it so it prints:

Last color: green
colors = ['red', 'blue', 'green']
last_index = len(colors)
print(f'Last color: {colors[last_index]}')
Exercise 5: Fix the ValueError
Fix the Bug

This code crashes when trying to convert a price string to an integer. Fix it so it prints:

Price in cents: 999

The price is "9.99" dollars, and we want to convert it to cents (multiply by 100 and turn the result into an integer).

price_str = '9.99'
price_cents = int(price_str) * 100
print(f'Price in cents: {price_cents}')
Exercise 6: Fix All the Bugs
Fix the Bug

This code breaks in each of its three sections, though one fix can solve two of them. Fix it so the output is:

Student: Alice
Grade: 85
Passed: True
# Bug 1: Something wrong with the variable name
student_name = 'Alice'
print(f'Student: {student_Name}')
# Bug 2: Something wrong with the type
grade = '85'
print(f'Grade: {grade + 0}')
# Bug 3: Something wrong with the comparison
passed = grade >= 60
print(f'Passed: {passed}')

Summary: Python Error Messages

Here's your quick reference for the most common Python errors:

ErrorMeaningFirst Thing to Check
SyntaxErrorBad code structureMissing colons, parentheses, quotes
NameErrorUnknown variableSpelling, definition order
TypeErrorWrong typeCheck types with type()
IndexErrorBad list indexList length, 0-based indexing
KeyErrorBad dict keyUse .get() with default
ValueErrorWrong valueValidate before converting

The golden rules of debugging:

  • Always read the last line of the traceback first
  • Check the line number Python gives you (and the line before it)
  • Use print(type(x), x) to inspect suspicious variables
  • Error messages are helpers, not enemies - they tell you exactly what went wrong
  • What's Next?

    Now that you can read error messages, you're ready to tackle more complex Python topics with confidence. Head to Python Lists to learn about one of Python's most powerful and versatile data structures.

    Harder problems

    More problems on this topic: Python Basics

    Related Tutorials

    Was this tutorial helpful?