You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

银行项目中如何实现while循环持续取用最新账户余额?

解决银行项目中余额无法累计更新的问题

问题根源

你的代码存在三个核心问题:

  • 没有维护实时余额的变量,每次循环都复用初始输入的金额,导致余额无法累计
  • deposit函数逻辑错误,硬调用withdrew(t, w)获取余额,而非使用最新账户状态
  • 取款函数可能返回字符串(余额不足提示),后续存款操作会触发类型错误

修改方案

  1. 用current_balance变量保存实时余额,替代原有的t
  2. 调整两个函数的参数,让它们接收当前余额作为输入,返回更新后的余额或提示信息
  3. 循环中每次操作后更新current_balance,确保下一次循环使用最新值
  4. 增加类型判断,处理余额不足的情况,避免后续操作报错

修改后的完整代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:20:40