The Secret Life of Python: The Safety Net ('try' and 'except')
Understanding try, except, and Input Validation.
Timothy was beaming. "I learned my lesson from last time," he told Margaret. "I updated my guessing game. Now I use int() to cast the user's input into a number immediately. No more silent bugs!"
"That is excellent progress," Margaret said, moving her chair closer. "But what happens if the user doesn't follow instructions?"
"What do you mean?" Timothy asked. "It says 'Guess a number'. Why wouldn't they type a number?"
"Users are creative," Margaret smiled. "Watch."
She leaned over and ran his program.
Prompt: Guess the number (1-10):
Margaret typed: five
Output:
Traceback (most recent call last):
File "game.py", line 3, in <module>
guess = int(input("Guess the number (1-10): "))
ValueError: invalid literal for int() with base 10: 'five'
The program crashed instantly.
Timothy sighed. "It blew up. Because int() doesn't know how to turn the word 'five' into a number."
Catching the Fall
"Exactly," Margaret said. "When Python encounters something it can't handle—like trying to do math with a word—it raises an Exception. By default, an exception stops the program dead in its tracks."
"So I need to force the user to type digits?" Timothy asked.
"You can't force them," Margaret corrected gently. "But you can catch them when they fall."
She drew a simple trapeze artist on the whiteboard with a net underneath. "Think of your code as a performance. Usually, the acrobat catches the bar perfectly. But sometimes, they slip. If there is no net, the show ends in disaster. If there is a net, they simply bounce back and try again."
"In Python," she continued, "we call this net a try / except block."
She took the keyboard and wrapped his risky code in a safety structure.
try:
# The risky move: Trying to cast text to a number
guess = int(input("Guess the number (1-10): "))
print(f"You guessed: {guess}")
except ValueError:
# The safety net: Catches ONLY the ValueError crash
print("Oops! Please type a digit, like '5', not the word 'five'.")
"Now watch," she said. She ran it again and typed five.
Output:
Oops! Please type a digit, like '5', not the word 'five'.
"It didn't crash!" Timothy said. "It just printed the message and... stopped."
The Infinite Patience
"But for a game," Timothy mused, "I don't want it to stop. I want it to ask me again until I get it right."
"Then we combine our Safety Net with a Loop," Margaret said. "This is a very common pattern called an Input Validation Loop."
She modified the code to be persistent.
while True:
try:
user_input = input("Guess the number (1-10): ")
guess = int(user_input)
# Challenge: Check if it's actually 1-10
if guess < 1 or guess > 10:
print("Please pick a number between 1 and 10.")
continue # Loop back to the start
# If we get here, it's a number AND it's in range!
break
except ValueError:
# If int() crashes, we jump here immediately.
print("That wasn't a valid number. Please try again.")
print(f"Great! You chose {guess}.")
Timothy ran it.
He typed five. -> Program: That wasn't a valid number.
He typed 99. -> Program: Please pick a number between 1 and 10.
He typed 7. -> Program: Great! You chose 7.
"It’s surprisingly patient," Timothy laughed.
"It is," Margaret agreed. "It creates a safe space where the user can make mistakes without breaking the whole application."
She added one final, serious note. "Notice that I wrote except ValueError. Never just write except: by itself."
"Why not?" Timothy asked. "Wouldn't it be easier to catch everything?"
"If you catch everything," Margaret warned, "you might catch things you didn't mean to—like the user trying to quit the program. You want a safety net for the acrobat, not a giant dome that traps everyone inside the building. Be specific."
Margaret’s Cheat Sheet
Margaret opened her notebook to the "Error Handling" section.
- The Concept: Exception Handling.
- The Keywords:
try: "Attempt this code, but watch out for errors."except: "If a specific error happens, run this code instead of crashing."The Pattern: The Input Loop.
Use
while Trueto keep asking.Use
breakto escape the loop only when the input is valid.The Golden Rule: Always catch specific errors (like
ValueError) rather than using a bareexcept:. You want to fix the error, not hide it.
Timothy nodded. "So the int() function isn't dangerous anymore. It just needed a spotter."
"Exactly," Margaret smiled. "And now, your game is truly user-friendly."
In the next episode, Margaret and Timothy will face "The Identity Crisis"—where Timothy discovers that two things can look exactly the same but still be completely different objects.
Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.
.jpeg)

Comments
Post a Comment