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
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 Must Use Functions for this!!!
set_money_bin_cash()
Arguments: NONE
Return: The Starting Cash Amount
withdraw_cash_from_bin(currentCash)
Arguments: The current amount of money in the bin
Returns:
The total amount withdrawn
set_adventurer_number()
Arguments: NONE
Returns: The total number of adventurers
calculate_adventurer_cash(cashTaken, numAdventurers)
Arguments:
How Much Cash was Taken Out
How Many Adventurers
Returns:
How much money per adventurer
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
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! Ye think I’m marchin’ into a trap-filled ruin alone?! Not on yer life, laddie! Every great adventure needs a proper crew — and I don’t tolerate any funny business when it comes to hiring!”
Scrooge has assembled a fixed list of approved adventurers for this expedition. Your job is to let the user select exactly ONE adventurer from the list.
⚠️ Important:
Scrooge refuses to accept:
Numbers that are outside the valid range
Words, symbols, or nonsense instead of numbers
Any attempt to pick an adventurer that isn’t on the list
If the user makes a mistake, Scrooge will yell at them and demand they try again.
REMEMBER! Adventurers don’t grow on trees—choose wisely!
Your program must:
Display a numbered list of available adventurers
Prompt the user to select one adventurer by number
Validate the user’s input:
If the input is not a number, Scrooge yells
If the number is too small or too large, Scrooge yells
Keep prompting the user until a valid selection is made
Confirm the chosen adventurer once selected correctly
"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!"
For each supply item, your program must:
Prompt the user to enter a quantity
Validate the input:
If the input is not a number, Scrooge yells
If the number is outside the allowed range, Scrooge yells
Keep prompting until a valid quantity is entered
Store the final accepted quantity
Confirm the purchase before moving on to the next item
"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 ancient map is enchanted and sealed by powerful magic. To unlock it, you must prove you have both wisdom and discipline — two things Scrooge insists are in short supply these days.
If you mess up? SCROOGE WILL SHOUT AT YOU UNTIL YOU GET IT RIGHT!
The Map's Secret Name:
Prompt the user to enter the secret name of the map
Validate the input:
If it contains anything other than letters, Scrooge yells
Keep prompting until the name is valid
The Ancient Access Code:
Prompt the user to enter the ancient access code
Validate the input:
If it contains anything other than numbers, Scrooge yells louder
Keep prompting until the code is valid
Once both inputs are correct, reveal the path to Duckopolis with a triumphant message
💡 “Bah! If I see a single number in that name, or a single letter in that code, I’ll need another cup o’ tea before dealin’ with this nonsense!”