回顾:对银行账户建模
Coddy 面向 R 开发者的 Python 课程的第 37 课,共 48 课。
挑战
入门实现 Account(owner, balance),初始整数余额必须为非负数。存储独立的实例状态。提供 deposit(amount) 和 withdraw(amount),两者都返回新余额。对于非正数金额以及大于余额的取款金额,抛出 ValueError,并保持状态不变。提供 __str__,格式为 owner:balance。输入包含两行 owner balance,然后是命令数量,接着是若干条命令 index action amount。索引为 0 或 1,操作为 deposit 或 withdraw,所有者名称不包含空格。驱动程序会打印每次操作后的新余额或 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)
面向 R 开发者的 Python中的所有课
自己练习: Python 在线编译器