Start free

Advanced · Classes · 192 of 264

Bank account

Write a class Account with deposit, withdraw and a balance. A withdrawal larger than the balance is refused with Insufficient funds. Process the commands.

Input: n, then n commands: deposit <x>, withdraw <x> or balance. Output: Insufficient funds for refused withdrawals, the balance for balance.

Examples

Input
5
deposit 100
withdraw 30
balance
withdraw 100
balance
Output
70
Insufficient funds
70
Input
1
balance
Output
0

One more test checks other inputs when you press Check.

Stuck? The idea behind classes

A class describes a kind of object: its data (attributes, set in __init__) and what it can do (methods). Each object made from it has its own data.

self is the object a method is called on; __str__ says how the object prints.

class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def pay_in(self, amount):
        self.balance += amount

acc = Account("Ann")
acc.pay_in(5)
print(acc.balance)

Watch for: Every method's first parameter is self, and attributes are reached through it: self.balance, not balance.

All the classes exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More classes exercises