Undefined
By: Guest | Date: Jun 6 2018 20:52 | Format: Python | Expires: never | Size: 1.28 KB | Hits: 711
- from decimal import Decimal
- class ATM:
- def __init__(self):
- self.balances = {}
- def deposit(self, customer, amount):
- amount = Decimal(amount)
- if amount <= 0:
- raise ValueError("Can only deposit positive amounts")
- if customer in self.balances:
- self.balances[customer] += amount
- else:
- self.balances[customer] = amount
- def withdraw(self, customer, amount):
- if customer not in self.balances:
- raise KeyError("No such customer: {}".format(customer))
- amount = Decimal(amount)
- balance = self.balances[customer]
- if amount > balance:
- raise ValueError("Overdraft")
- self.balances[customer] = balance - amount
- if __name__ == '__main__':
- atm = ATM()
- atm.deposit('alice', '1200.63')
- atm.deposit('bob', '686.95')
- try:
- atm.deposit('carol', '-13')
- assert False, "Should have raised ValueError"
- except ValueError:
- pass
- atm.deposit('bob', '.05')
- assert atm.balances['bob'] == 687
- atm.withdraw('alice', '.63')
- assert atm.balances['alice'] == 1200
- try:
- atm.withdraw('danica', '12')
- assert False, "Should have raised KeyError"
- except KeyError:
- pass
Latest pastes
1 days ago
1 days ago
11 months ago
13 months ago
17 months ago