回顾:模拟银行账户
Coddy 面向 GDScript 开发者的 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)
面向 GDScript 开发者的 Python中的所有课
自己练习: Python 在线编译器