Run an account with its own kinds of error.
What to build
Two custom exceptions, raised by a function and handled by its caller.
Requirements
- Define
BadAmountandNotEnough, both inheriting fromException. deposit Xandwithdraw Xchange the balance, which starts at 0.- An amount of 0 or less raises
BadAmount. PrintRefused: bad amount. - Withdrawing more than the balance raises
NotEnoughwith the shortfall. PrintRefused: need X more. - Count every command with
finally, and finish withBalance BandProcessed P.
Input
The first line has n. Each of the next n lines is deposit X or withdraw X.
Output
One line for each refusal, then the two final lines.
Constraints
n is from 1 to 100. Each X is a whole number from -1000 to 100000.
Example
Input:
3
deposit 100
withdraw 150
withdraw 30
Output:
Refused: need 50 more
Balance 70
Processed 3
Why it works
Each exception names one kind of problem, so the caller's except blocks stay simple. finally counts a command however it ended.
Examples
Example 1 · Input
3 deposit 100 withdraw 150 withdraw 30
Expected output
Refused: need 50 more Balance 70 Processed 3
Example 2 · Input
2 deposit -5 withdraw 0
Expected output
Refused: bad amount Refused: bad amount Balance 0 Processed 2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Define two classes that inherit from Exception.
Hint 2
In withdraw, check for a bad amount first and then for too little money.
Hint 3
Put processed += 1 in a finally block.
Solution
Show one correct solution (try it yourself first)
class BadAmount(Exception):
pass
class NotEnough(Exception):
pass
balance = 0
def apply(command, amount):
global balance
if amount <= 0:
raise BadAmount()
if command == "deposit":
balance += amount
else:
if amount > balance:
raise NotEnough(amount - balance)
balance -= amount
n = int(input())
processed = 0
for _ in range(n):
command, text = input().split()
try:
apply(command, int(text))
except BadAmount:
print("Refused: bad amount")
except NotEnough as error:
print(f"Refused: need {error} more")
finally:
processed += 1
print("Balance", balance)
print("Processed", processed)