By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
You've learned Python fundamentals separately: variables, loops, functions, dictionaries, conditionals. Now you need to combine them into a working program that handles real-world messiness. The problem is that real code fails—users enter bad data, divide by zero, pass wrong types. You need error handling to catch these failures gracefully instead of crashing.
The try/except pattern wraps risky code and specifies what to do when it breaks. You write the code that might fail inside try. If it fails, Python jumps to the except block that matches the error type.
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError as e:
return f"Type error: {e}"
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # Cannot divide by zeroNotice the pattern: you can catch specific exceptions (ZeroDivisionError, TypeError) and handle each one differently. You can also capture the error message with as e and include it in your response. This beats crashing and gives users useful feedback.
Your final project combines everything. Build a program that stores student names and scores in a dictionary, calculates averages, assigns letter grades (A for 90+, B for 80+, C for 70+, F below 70), and prints a formatted report. Handle the edge case where a student has no scores using try/except so the program doesn't crash when calculating an average.
This project forces you to use variables for data, loops to process students, functions to calculate and assign grades, dictionaries to organize data, conditionals for grade logic, and error handling for robustness. It's a realistic program that does something useful.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.