Today, we're theming the lesson after the 2017 reboot of DUCKTALES!
You will learn to use try/except to handle errors in Python programs
These are used to catch ERRORS, which can happen when we try to do things which shouldn't work
Remember... errors happen. Whether it's our code, user input, etc.
We have to be ready to stop these, so our program doesn't crash!
"Scrooge McDuck’s crew is after the Lost Relic of Duckopolis, hidden in a trap-filled ruin! Errors could doom the quest—try and except are our lifeline."
What Are Exceptions?
Errors that can crash a program
Why they Matter?
To Keep Programs running smoothly
How to Handle Them?
Try/Except Blocks
Let's Look at the 2 ways we typically use TRY/EXCEPT Blocks...
One Time Use
Looped Use for Valid Input
This will make sure your program doesn't crash if it encounters a specific error
This will loop. It essentially makes the user enter valid input
If you want a number, they need to enter a number
If you want alpha, they need to enter alpha
Write a Program which will:
Set the starting amount of money in Scrooge McDuck's Money Bin.
Ask the user how much money should be withdrawn for the adventure
Once Done, ask for how many adventurers are on the expedition
Then, calculate the total amount of cash that each adventurer should get!
THIS WILL BE THE BASE PROGRAM WITH NO ERROR CHECKING!!!
YOU NEED TO USE FUNCTIONS FOR THIS!!!!
set_money_bin_cash()
withdraw_cash_from_bin()
set_adventurer_number()
calculate_adventurer_cash()
Here's Your Expected Output...
As you can see, there are many types of errors we can have happen in our program. There are some examples below, followed by a larger list.
ValueError
What It Is: Raised when a function gets an argument of the right type but an inappropriate value.
ZeroDivisionError
What It Is: Raised when dividing by zero
IndexError
What It Is: Raised when accessing a list index that doesn’t exist.
TypeError
What It Is: Raised when an operation or function is applied to an object of the wrong type.
This is not an exhaustive list. There are a LOT more!! You'll need to look those up to find out!
In Python, the raise statement lets you throw an exception on purpose—like Scrooge tossing a tantrum when his nephews mess up! It’s your way to say, “Nope, this won’t do!” and trigger an error for the try/except block to catch.
For example:
If Webby’s mission code has numbers, you can raise ValueError to make her yell, “Numbers in my code? Unacceptable!”
Use it to enforce rules (e.g., “only letters!” or "only numbers")
The .isdigit() method returns True if the string contains only digits (0-9) and is non-empty, False otherwise (e.g., letters, spaces, decimals, or symbols fail).
Why: It’s stricter than just catching ValueError with int(), as it prevents decimals or negatives if desired.
The .isalpha() method returns True if the string contains only letters (a-z, A-Z) and is non-empty, False otherwise (e.g., numbers, spaces, or symbols fail).
Why: It ensures pure alphabetic input, fitting the narrative of a “code name.”
Now, it's time to implement some basic error checking in our program!
You need to modify the program you've written to do the following:
Anywhere user input is required, you need to validate their input
EVERY FUNCTION MUST HAVE ERROR CHECKING!!!
Make sure that it doesn't crash your program!
You either need to end, or keep re-prompting the user to enter the right type!
Every Time There is INVALID Input, you MUST have Scrooge Yell a random phrase at You!!
Here is some sample output showing what now happens when the user enters wrong data when prompted. Notice, the program doesn't crash!
This is just one version where it makes the user re-enter values! You can also gracefully close the program when they enter bad data!
"Great globs of gold! You think I’m going into a trap-filled ruin alone?! Not on yer life, laddie! Every great adventure needs a top-notch crew, and lucky for you, I’ve got some of the best explorers in the business. But be careful! If you pick someone who isn’t on the list, I won’t stand for any of this 'mystery adventurer nonsense!'
It’s your job to pick one member from our fearless band of treasure hunters. But don’t get cheeky—if you enter something ridiculous like a number that’s too high, or—heaven forbid—you type words instead of numbers, I’ll have words for ye!
Objective:
Display the list of adventurers.
Ask the user to select one by number.
If they pick a number outside the valid range, Scrooge will yell at them!
If they type nonsense instead of a number, Scrooge will yell even louder!
Keep prompting until they pick correctly.
REMEMBER! Adventurers don’t grow on trees—choose wisely!
"You think I got rich by wastin’ money on useless junk?! HAH! But an adventure like this calls for supplies! And I don’t mean one measly torch and a bit of string—I mean real adventuring gear fit for surviving cursed tombs and dodging booby traps!"
Here’s the deal, kid:
You need to buy supplies for the expedition—but there’s a catch!
If you try to buy too many items, Scrooge will yell at you for wasting money!
If you enter something ridiculous like a banana emoji instead of a number, Scrooge is gonna LOSE IT!
Keep asking the user for a valid number until they get it right.
Supply List:
Rope (1-5) → "No adventurer survives without rope!"
Torches (1-10) → "Ever been in a dark ruin? No? Well, you’ll need light!"
Healing Potions (1-3) → "Better safe than cursed!"
"I expect ye to spend wisely, or so help me, I’ll make ye count every last coin yerself!"
"Ahh, the Lost Map of Duckopolis! This map will lead us to the grandest treasure in all the land! But, of course, it wouldn’t be a legendary artifact if it didn’t have a trick to it!"
This map is enchanted!
To unlock it, you must enter the ancient map’s secret name. But be warned! The map only understands real names—no numbers, no nonsense!
Then, you’ll need to enter the ancient access code. This must be a number—no letters, no symbols, and DEFINITELY no emojis!
If you mess up? SCROOGE WILL SHOUT AT YOU UNTIL YOU GET IT RIGHT!
Objective:
Ask the user for the name of the map (letters only).
If they enter numbers instead of letters, Scrooge scolds them mercilessly!
Ask the user for the secret access code (numbers only).
If they enter letters instead of numbers, Scrooge questions their intelligence!
Once both inputs are correct, the path to Duckopolis is revealed!
"Bah! If I see a single number in that name, or a single letter in that code, I’m gonna need another cup of tea before I deal with this nonsense!"