Simulate a bank account that starts at 0. Process each command in order. A withdrawal larger than the balance is refused: print Not enough money and leave the balance unchanged. At the end, print the balance.
What to build
A class whose methods enforce the rule about withdrawing.
Requirements
- Process each command in order.
- Refuse a withdrawal larger than the balance, printing
Not enough money. - Print the final balance.
Input
The first line has n (1 to 100). Each of the next n lines is deposit X or withdraw X, where X is a whole number from 1 to 100000.
Output
One line Not enough money for each refused withdrawal, then the final balance.
Constraints
n is from 1 to 100, and each X is from 1 to 100000.
Example
Input:
3
deposit 500
withdraw 800
withdraw 200
Output:
Not enough money
300
Why it works
Putting the rule inside withdraw means that it is applied every time, by every caller.
Examples
3 deposit 500 withdraw 800 withdraw 200
Not enough money 300
1 withdraw 5
Not enough money 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Change self.balance inside the methods.
Hint 2
Check amount > self.balance before withdrawing.
Solution
Show one correct solution (try it yourself first)
class Account:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough money")
else:
self.balance -= amount
acc = Account()
n = int(input())
for _ in range(n):
command, amount = input().split()
if command == "deposit":
acc.deposit(int(amount))
else:
acc.withdraw(int(amount))
print(acc.balance)