Objective
Create a Python program that simulates a bank transaction: if something goes wrong inside the block, the balance goes back to its previous value. For that, __exit__ can decide what to do with the error.
Instructions
- Create the class
Account(with abalanceattribute) and the classTransaction, a context manager that on entering stores a copy of the balance and returns the account. - In
__exit__, if there was an error (the first parameter is notNone) restore the balance, showRolled back: messageand returnTrueto suppress the error. If there was no error, returnFalse. - Read the initial balance, an integer
nandnoperations with the format+ amountor- amount(for example- 200). Each one runs inside a transaction. - If subtracting leaves the balance negative, raise
ValueErrorwith the messageinsufficient balance(after subtracting). After each operation showBalance: s.
100
3
+ 50
- 200
- 30
Balance: 150
Rolled back: insufficient balance
Balance: 150
Balance: 120
Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.
Start exercise