Menu
CoddyTech

回顾:为银行账户建模

Coddy 面向 Ruby 开发者的 Python 课程的第 37 课,共 48 课。

challenge icon

挑战

入门

实现 Account(owner, balance),初始整数余额必须非负。存储各实例独立的状态。提供 deposit(amount) 和 withdraw(amount),每个方法都返回新余额。金额必须为正数,取款金额不得超过余额,否则应引发 ValueError,并保留原状态。提供 __str__,格式为 owner:balance。输入包含两行 owner balance,接着是命令数量,然后是若干条 index action amount 命令。Index 为 0 或 1,action 为 deposit 或 withdraw,owner 中不含空格。驱动程序会打印每次操作后的新余额或 invalid,然后按输入顺序打印两个账户。

锁定的驱动程序会读取输入并打印结果。只提交所需的类和函数定义,不要在你的答案中读取输入或打印内容。API 名称必须与指定名称完全一致。

你的代码应写在可编辑文件 account.py 中。driver.py 包含提供的输入输出代码和 API 检查,无法编辑。保留提供的导入语句,不要在可编辑模块中读取输入或打印内容。

亲手试试

from account import Account

accounts = []
for _ in range(2):
    owner, amount = input().split()
    accounts.append(Account(owner, int(amount)))
for _ in range(int(input())):
    index, action, amount = input().split()
    account = accounts[int(index)]
    try:
        if action == "deposit":
            print(account.deposit(int(amount)))
        else:
            print(account.withdraw(int(amount)))
    except ValueError:
        print("invalid")
for account in accounts:
    print(account)

面向 Ruby 开发者的 Python中的所有课

自己练习: Python 在线编译器