银行项目中如何实现while循环持续取用最新账户余额?
解决银行项目中余额无法累计更新的问题
问题根源
你的代码存在三个核心问题:
- 没有维护实时余额的变量,每次循环都复用初始输入的金额,导致余额无法累计
deposit函数逻辑错误,硬调用withdrew(t, w)获取余额,而非使用最新账户状态- 取款函数可能返回字符串(余额不足提示),后续存款操作会触发类型错误
修改方案
- 用
current_balance变量保存实时余额,替代原有的t - 调整两个函数的参数,让它们接收当前余额作为输入,返回更新后的余额或提示信息
- 循环中每次操作后更新
current_balance,确保下一次循环使用最新值 - 增加类型判断,处理余额不足的情况,避免后续操作报错
修改后的完整代码
def withdrew(current_balance, w): if current_balance > w: return current_balance - w else: return "Not enough money to withdraw." def deposit(current_balance, d): return current_balance + d current_balance = int(input("What is your total amount: ")) is_game_on = True while is_game_on: # 取款操作 w = int(input("How much amount you would like to withdraw? ")) withdraw_result = withdrew(current_balance, w) if isinstance(withdraw_result, int): current_balance = withdraw_result print(f"Your current balance is {current_balance}") else: print(withdraw_result) # 存款操作 d = int(input("How much you would like to deposit? ")) current_balance = deposit(current_balance, d) print(f"Your new balance is {current_balance}") # 询问是否继续 user = input("Would you like to continue? Enter 'y' or 'n': ").lower() if user != 'y': is_game_on = False
测试示例
What is your total amount: 100 How much amount you would like to withdraw? 10 Your current balance is 90 How much you would like to deposit? 100 Your new balance is 190 Would you like to continue? Enter 'y' or 'n': y How much amount you would like to withdraw? 10 Your current balance is 180 How much you would like to deposit? 50 Your new balance is 230 Would you like to continue? Enter 'y' or 'n': n
内容的提问来源于stack exchange,提问作者Trishna
相关产品推荐
相关产品推荐

