Python银行登录程序中balance变量无法保留值问题求助
问题分析与解决方案
你的问题核心是每次操作后没有更新balance变量本身:你在取款、存款时计算了新余额存在total里,但始终没把新值赋值回balance,导致balance一直保持初始的100,每次操作都基于原始值计算,看起来像是被重置了。
修改后的代码
import time username = "user" password = "123" login_count = 0 while True: login_count += 1 if login_count > 3: print("try again later") break user = input("what is your username? ") pas = input("what is your password? ") if user == username and pas == password: print("login in...") time.sleep(2) print("correct!") break balance = 100 while True: if login_count > 3: break option = input("\nwould you like to do: \nwithdraw \ndeposit \nview \nexit \n ").strip().lower() if option == "withdraw": withdraw = float(input("how much would you like to withdraw? ")) if balance - withdraw < 0: print("you cannot take out that much") continue balance -= withdraw print("here is your new balance: ", balance) elif option == "deposit": deposit = float(input("how much would you like to deposit? ")) balance += deposit print("here is your new balance: ", balance) elif option == "view": print("here is your balance: ", balance) elif option == "exit": print("login out...") time.sleep(2) print("thank you for being a loyal customer!") break else: print("Invalid option, please try again.")
关键修改点
- 取款/存款操作:直接用
balance -= withdraw、balance += deposit更新余额,不再依赖临时变量,确保balance实时保存最新值 - 输入优化:
strip().lower()让用户输入的大小写、前后空格不影响功能判断(比如输入" Withdraw "也能被识别) - 新增无效选项提示,避免用户输入错误后无反馈
修改后balance会在每次操作后保留更新值,直到程序退出。
内容的提问来源于stack exchange,提问作者Mozza
相关产品推荐
相关产品推荐

