Python存款功能while True循环条件判断错误排查求助
问题排查与修复
核心错误分析
- 非法输入判断逻辑完全错误:第二个
if条件用and连接deposit < 0和deposit > 100000,一个数值不可能同时满足这两个条件,导致continue永远不会触发。无论输入合法与否,程序都会执行后续的余额计算和打印操作。 - 缺少合法输入后的循环退出机制:即使输入符合要求,
while True会持续循环请求输入,无法正常结束流程。
修正后的代码
balance = 30000 choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawal\n:")) if choice == 1: print("Your balance is $", balance) elif choice == 2: while True: deposit = float(input("Enter the deposit you would like to make:")) if deposit < 0 or deposit > 100000: print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.") continue newbalance = deposit + balance print("Your balance is $", newbalance) break
修正说明
- 移除无效的
if(deposit < 0 and deposit > 100000)判断,改为在检测到非法输入时直接continue,让程序重新提示用户输入,跳过后续计算逻辑。 - 合法输入处理完成后添加
break,跳出while循环,结束存款流程。 - 将第二个独立
if改为elif,减少不必要的条件判断,优化代码逻辑。 - 修正拼写错误
withdrawl为withdrawal,保证表述规范。
内容的提问来源于stack exchange,提问作者Dontray Blackwood
相关产品推荐
相关产品推荐

