AiTechWorlds
AiTechWorlds
Every programmer, without exception, writes code that breaks. Beginners see an error message and panic. Experienced programmers see an error message and think: "Excellent. Python just told me exactly where and why something went wrong."
Error messages are not insults. They're diagnostic reports. Learning to read them is one of the highest-value skills you can develop.
When Python encounters an error, it displays a traceback. Let's look at one:
Traceback (most recent call last):
File "calculator.py", line 12, in <module>
result = divide(10, 0)
File "calculator.py", line 5, in divide
return a / b
ZeroDivisionError: division by zero
This traceback has three parts:
1. The call stack (from top to bottom, outermost to innermost)
File "calculator.py", line 12, in <module>
result = divide(10, 0) ← This called the function
File "calculator.py", line 5, in divide
return a / b ← This is where it actually broke
2. The error type
ZeroDivisionError
3. The error message
division by zero
Always read a traceback from the bottom up. The bottom line tells you the type and message. The lines above show how the program got there.
if score > 90
print("Excellent")
Error:
SyntaxError: expected ':'
A colon is missing after the if condition. Python couldn't even run the file — it rejected the code before executing a single line.
Common causes:
: after if, for, while, def, class(, [, {print(username) # username was never defined
Error:
NameError: name 'username' is not defined
Either you made a typo, forgot to create the variable, or used it before assigning it.
user_name = "Alice"
print(username) # Typo! Should be user_name
Fix: Check spelling carefully. Python is case-sensitive: Name, name, and NAME are three different things.
age = "25"
print(age + 1)
Error:
TypeError: can only concatenate str (not "int") to str
You tried to add a string and a number. Python doesn't guess your intention.
Fix: Convert the type:
age = int("25")
print(age + 1) # 26
fruits = ["apple", "banana", "cherry"]
print(fruits[5]) # Only indices 0, 1, 2 exist
Error:
IndexError: list index out of range
Fix: Check the list length before accessing. Indices go from 0 to len(list) - 1.
if 5 < len(fruits):
print(fruits[5])
else:
print("Index doesn't exist")
student = {"name": "Alice", "grade": 10}
print(student["age"]) # "age" key doesn't exist
Error:
KeyError: 'age'
Fix: Use .get() which returns None (or a default) instead of crashing:
age = student.get("age", "Not specified")
print(age) # Not specified
age = int("twenty") # "twenty" can't become an integer
Error:
ValueError: invalid literal for int() with base 10: 'twenty'
Fix: Validate input before conversion:
age_input = input("Your age: ")
if age_input.isdigit():
age = int(age_input)
else:
print("Please enter a number")
number = 42
number.upper() # Integers don't have .upper()
Error:
AttributeError: 'int' object has no attribute 'upper'
Fix: Check what type your variable actually is with type(variable).
| Error | Cause | Common Fix |
|---|---|---|
SyntaxError | Code can't be parsed | Check colons, brackets, quotes |
NameError | Variable not defined | Check spelling and scope |
TypeError | Wrong type for operation | Convert types explicitly |
IndexError | List index out of bounds | Check len() first |
KeyError | Dictionary key missing | Use .get() method |
ValueError | Right type, invalid value | Validate before converting |
AttributeError | Method/attribute doesn't exist | Check variable's type |
ZeroDivisionError | Division by zero | Check divisor before dividing |
IndentationError | Wrong indentation | Use consistent spaces (4 recommended) |
FileNotFoundError | File doesn't exist | Check file path and name |
When your code breaks, follow this order:
Step 1: Read the last line of the error first The error type and message tell you what went wrong.
Step 2: Find the file and line number
File "app.py", line 23, in calculate_tax
Line 23 of app.py, inside the calculate_tax function.
Step 3: Read the code at that line Look at what's actually written. Is it what you intended?
Step 4: Add print statements to inspect values
def calculate_tax(income, rate):
print(f"DEBUG: income={income}, type={type(income)}") # Add this
print(f"DEBUG: rate={rate}, type={type(rate)}") # Add this
return income * rate
Step 5: Think about what value you EXPECTED vs what you GOT The mismatch tells you where the logic went wrong.
try/except to Handle Expected ErrorsSometimes you know an error might happen and want to handle it gracefully:
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Cannot divide by zero")
return None
except TypeError:
print("Error: Both values must be numbers")
return None
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # Error: Cannot divide by zero → None
print(safe_divide(10, "2")) # Error: Both values must be numbers → None
try/except doesn't prevent errors — it catches them and lets you respond gracefully instead of crashing.
Here's a buggy function. Let's debug it together:
def calculate_average(scores):
total = 0
for score in scores:
total = total + score
average = total / len(scores)
return average
student_scores = [] # Empty list!
result = calculate_average(student_scores)
print(f"Average: {result}")
Error:
ZeroDivisionError: division by zero
Diagnosis: len(scores) is 0 when the list is empty. Division by zero.
Fix:
def calculate_average(scores):
if not scores: # Check for empty list
return 0
total = sum(scores)
return total / len(scores)
student_scores = []
result = calculate_average(student_scores)
print(f"Average: {result}") # Average: 0
student_scores = [78, 92, 65, 88]
result = calculate_average(student_scores)
print(f"Average: {result}") # Average: 80.75
Defensive programming — checking edge cases like empty lists, zero values, and unexpected inputs — is what separates good code from fragile code.
Errors are not failures. They're feedback. Every error message Python shows you is Python trying to help. Learn to read them calmly, and debugging becomes a puzzle to solve rather than a crisis to survive.
Now we're ready for the final project — putting everything together.
Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises