Part 9: Space Shields Up — Handling Errors
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
Part 9: Space Shields Up — Handling Errors
The Adventures of Ava the Astronaut: Learning Python One Planet at a Time
Houston, We Have a Problem
Ava was feeling confident. Her programs could make decisions, repeat tasks, store data in complex structures, and even save information to files. She was in the middle of writing a new program to calculate the fuel needed for a jump to lightspeed.
print("--- Light-speed Fuel Calculator ---")distance = input("Enter distance in light-years: ")fuel_needed = int(distance) * 5print(f"You will need {fuel_needed} units of fuel.")She ran the program. The prompt appeared: Enter distance in light-years:. She typed 100. The output was perfect: You will need 500 units of fuel.
Then she ran it again, but this time she accidentally typed one hundred instead of 100. The program immediately stopped, and a huge, scary-looking error message filled the screen:
Traceback (most recent call last): File "main.py", line 3, in <module> fuel_needed = int(distance) * 5ValueError: invalid literal for int() with base 10: 'one hundred'Her program had crashed. It hit an unexpected problem — an error (also called an exception) — and did not know what to do. It is like a spaceship hitting an unexpected asteroid: without shields, the ship is destroyed.
Understanding the Error Message
Before we fix the problem, let’s learn to read the error message. It is not as scary as it looks — it is actually very helpful!
| Part of the Error | What It Means |
|---|---|
Traceback (most recent call last): | Python is showing you the path it took to reach the error. |
File "main.py", line 3 | The error occurred in the file main.py, on line 3. |
fuel_needed = int(distance) * 5 | This is the exact line of code that caused the problem. |
ValueError | This is the type of error. A ValueError means a function received a value it cannot work with. |
invalid literal for int()... | A human-readable description of what went wrong: int() cannot convert the text “one hundred” into a number. |
The try...except Block: Your Program’s Shield
“Py, my program crashed!” Ava cried. “A single wrong input and the whole thing breaks down.”
“That is why we must raise the shields, Commander,” Py said. “In Python, our shield is the try...except block. It allows you to try running a block of code that might cause an error. If an error occurs, the program does not crash. Instead, it jumps to the except block, where you can handle the problem gracefully.”
Let’s rebuild the fuel calculator with shields up.
print("--- Light-speed Fuel Calculator (Shields Up!) ---")distance_str = input("Enter distance in light-years: ")
try: # We TRY to do the potentially dangerous operation distance_int = int(distance_str) fuel_needed = distance_int * 5 print(f"You will need {fuel_needed} units of fuel.")except ValueError: # This code ONLY runs if a ValueError occurs in the try block print("Error: Invalid input. Please enter a number, not text.")
print("Calculator program finished. No crashes!")What happens now?
If the user types 100, the try block succeeds, the fuel is calculated, and the except block is completely skipped. But if the user types one hundred, the int() function causes a ValueError. Instead of crashing, the program immediately jumps to the except ValueError: block and prints the helpful error message. Then it continues to the final print statement. The program survived!
Catching Different Kinds of Asteroids
There are many different types of errors in Python, just like there are different types of space debris. Here are the most common ones you will encounter:
| Error Type | When It Happens | Example |
|---|---|---|
ValueError | A function gets a value of the right type but wrong content. | int("hello") |
TypeError | An operation is used on the wrong data type. | "hello" + 5 |
ZeroDivisionError | You try to divide a number by zero. | 10 / 0 |
FileNotFoundError | You try to open a file that does not exist. | open("ghost.txt", "r") |
KeyError | You try to access a dictionary key that does not exist. | my_dict["missing_key"] |
IndexError | You try to access a list index that is out of range. | my_list[99] (if list is shorter) |
You can set up multiple except blocks to handle different types of errors with different responses.
try: numerator = int(input("Enter a number to divide: ")) denominator = int(input("Enter a number to divide by: ")) result = numerator / denominator print(f"The result is {result}")except ValueError: print("Error: Please enter valid whole numbers.")except ZeroDivisionError: print("Error: You cannot divide by zero! The universe would implode.")The Full Shield: try-except-else-finally
Python’s error handling has a few more optional parts that give you even finer control.
try: number = int(input("Enter a number: "))except ValueError: print("That was not a valid number.")else: # This block runs ONLY if the try block succeeded (no error) print(f"Great! You entered {number}.")finally: # This block runs NO MATTER WHAT — error or no error print("Thank you for using the calculator.")| Block | When It Runs |
|---|---|
try | Always runs first. Contains the “risky” code. |
except | Runs only if an error occurs in the try block. |
else | Runs only if the try block succeeded without errors. |
finally | Always runs, regardless of whether an error occurred or not. Great for cleanup tasks. |
Combining Loops and Error Handling
A very common and powerful pattern is to combine a while loop with try...except to keep asking the user for input until they give a valid answer.
while True: try: age = int(input("Enter your age: ")) break # If we get here, the input was valid. Exit the loop. except ValueError: print("That's not a valid age. Please enter a number.")
print(f"Your age is {age}. Thanks!")This loop will keep asking for the age until the user enters a valid integer. It is a very robust pattern that you will use often in real programs.
Mini-Project: “The Unbreakable Space Console”
Your mission is to create a robust program that asks the user for their age and calculates what year they will turn 100 years old. Your program must not crash, no matter what the user types in.
Your Task:
- Use a
while Trueloop to keep asking for input until it is valid. - Inside the loop, ask the user to enter their current age.
- Use a
try...exceptblock to catchValueError. - If the input is valid, calculate the year they will turn 100 (assume the current year is 2026).
- Print the result in a friendly message (e.g., “You will turn 100 in the year 2076!”).
- If the input is invalid, print a clear error message and let the loop ask again.
Bonus Challenge: Add an additional check — after successfully converting to an integer, verify that the age is a positive number and less than 150. If not, print a message like “Please enter a realistic age.” without crashing.
Mission Complete!
Your programs are now battle-hardened! You have learned how to anticipate and handle errors using try...except blocks, preventing your programs from crashing and providing a much better experience for the user. You know how to catch specific error types, use else and finally for finer control, and combine error handling with loops for robust input validation.
You have now learned all the core building blocks of Python. For your final mission, you will combine everything into a capstone project: a text-based space adventure game! Get ready for “The Grand Mission” in Part 10!
This is Part 9 of a 10-part series: “The Adventures of Ava the Astronaut: Learning Python One Planet at a Time.”