Error handling
- Python course
- Beginner
- Lesson 115/116
- 6 min
Add input validation with try/except.
Error handling: guard the empty list
In this lesson you will guard against the empty list error with try/except. Division on an empty list sum([]) / len([]) raises a division-by-zero error:
empty = []
try:
result = sum(empty) / len(empty)
except ZeroDivisionError:
print("boş liste")
else:
print(result)The starting code includes the previous solutions. You will add the empty list and the try/except block. Since empty is empty, the except block runs and prints boş liste.
This makes the app more robust.
Practice Write try/except for the empty list
Write empty = []. Inside a try: block write result = sum(empty) / len(empty). Inside an except ZeroDivisionError: block write print("boş liste"). Inside an else: block write print(result).
Starter code
# Grade calculator - grades list
grades = [85, 90, 78]
print(grades)
grades.append(95)
print("eklendi:", len(grades))
average = sum(grades) / len(grades)
print("ortalama:", average)
# write try/except for the empty listSample solution
grades = [85, 90, 78]
print(grades)
grades.append(95)
print("eklendi:", len(grades))
average = sum(grades) / len(grades)
print("ortalama:", average)
empty = []
try:
result = sum(empty) / len(empty)
except ZeroDivisionError:
print("boş liste")
else:
print(result)Expected output
[85, 90, 78] eklendi: 4 ortalama: 87.0 boş liste
Next step: putting it together
Error handling is ready — the app no longer crashes on an empty list. In the final lesson you will combine everything with functions: you will define and call a hesapla function.
This final layer will make the code reusable and organised. Functions are the fundamental way to break code into parts and make it testable. All the pieces of the project now come together.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the except type
try:
result = sum(empty) / len(empty)
except ____:
print("boş liste")
try:
result = sum(empty) / len(empty)
except ZeroDivisionError:
print("boş liste")
Explanation: ZeroDivisionError is the division-by-zero error.
2 What does sum(empty) / len(empty) do when empty = []?
- Raises ZeroDivisionError Correct answer
- Returns 1
- Returns None
- Returns 0
Explanation: len([]) is zero; division by zero raises ZeroDivisionError.
3 Match error handling
| Term | Meaning |
|---|---|
try |
Protected code |
except |
Catches the error |
ZeroDivisionError |
Division by zero |
else |
Success block |