Python字符串if判断失效 交易模拟程序逻辑bug排查
问题核心原因
你的字符串判断失效完全是对Pythonor运算符的用法理解错误导致的:
- Python中所有非空字符串都属于布尔真值,
a or b的运算逻辑是返回第一个为真的值,不是“匹配a或者匹配b”的意思 - 你写的
proceed1 = "Checking" or "checking"执行后,proceed1只会被赋值为第一个真值也就是"Checking",永远不会匹配小写的"checking" - 同理
deposit、withdraw、proceed2几个变量都只会存储首字母大写的那个字符串,只要用户输入小写内容就会匹配失败,出现分支跳转错乱的问题 - 额外逻辑bug:取款分支的余额计算写反了,你写的
checking = withdraw1 - checking会得到负数余额,正确逻辑应该是原有余额减去取款金额;原代码只判断余额为0的情况,没有覆盖余额大于0但不足取款额的场景
修正方法
不用提前定义那些带or的匹配变量,更稳妥的写法是把用户输入统一转为小写(或大写)后再做判断,不管用户输入大小写都能正常匹配,同时修正余额计算逻辑。修正后的完整代码如下:
import time checking = 0 savings = 0 time.sleep(1) print("Thank you for choosing the Bank of Kegan") time.sleep(1) choice = input("Type \"Deposit\" or \"Withdraw\" \n ").lower() if choice == "deposit": print("Deposit Transaction Initiated") time.sleep(.5) print("Please choose an account you would like to Deposit into. ") account_choice = input("Type \"Checking\" or \"Savings\" \n ").lower() if account_choice == "checking": print("Checking Account Loading... \n") time.sleep(2) print("Checking: $", checking, "\n") time.sleep(2) amount1 = int(input("Please type how much you'd like to deposit. \n ")) time.sleep(.5) print("$", amount1, "Transaction Pending...") time.sleep(2) checking += amount1 print("Your new balance is: ") print("$", checking) elif account_choice == "savings": print("Savings Account Loading... ") time.sleep(2) print("Savings: $", savings) time.sleep(2) amount2 = int(input("Please type how much you'd like to deposit. \n ")) time.sleep(.5) print("$", amount2, "Transaction Pending... ") time.sleep(2) savings += amount2 print("Your new balance is: ") print("$", savings) else: print("Please choose a valid argument ") elif choice == "withdraw": print("Withdraw Transaction Initiated") print("Type what account you would like to withdraw from. ") choice2 = input("Checking or Savings\n").lower() if choice2 == "checking": print("Checking Account Loading... ") time.sleep(2) print("Checking \n Balance: ", checking) withdraw1 = int(input("Type how much you would like to withdraw. ")) print("$", withdraw1, "withdraw transaction pending... ") time.sleep(2) if checking < withdraw1: print("Insufficient balance, please check your account and try again.") else: checking -= withdraw1 print("your new balance is: $", checking) elif choice2 == "savings": time.sleep(.5) print("Savings Account Loading... ") time.sleep(2) print("Savings \n Balance: ", savings) withdraw2 = int(input("Type how much you would like to withdraw. ")) print("$", withdraw2, "withdraw transaction pending... ") time.sleep(2) if savings < withdraw2: print("Insufficient balance, please check your account and try again.") else: savings -= withdraw2 print("your new balance is: $", savings) else: print("Please choose a valid argument.")
额外优化点说明
- 去掉了
input()外面多余的str()转换,input()函数本身返回值就是字符串类型,不需要重复转换 - 把余额为0就提示没钱的判断改成了判断余额是否小于取款额,补上了余额大于0但不够取的逻辑漏洞
- 用
+=、-=运算符简化余额计算的写法,更符合Python编码习惯 - 去掉了多余的
exit()调用,分支执行完会自动结束对应逻辑,不需要手动退出
内容的提问来源于stack exchange,提问作者Kegan Bergeron
相关产品推荐
相关产品推荐

