if语句判断异常求助:输入1未触发对应分支
问题分析与解决方案
哈哈,这个问题我刚学Python的时候也踩过一模一样的坑!核心原因特别简单:input()获取到的用户输入是字符串类型,而你在判断条件里把它和整数1做比较——字符串"1"和整数1在Python里是完全不同的两种数据类型,所以roomChoice == 1永远不会成立,程序自然就走到else分支打印你输入的内容了。
怎么解决?
- 先把输入的内容转换成整数类型,再进行判断:
roomChoice = int(input("Choose 1-3: ")) if roomChoice == 1: # 额外提一句:原代码直接用+拼接数字和字符串会报错,用f-string更稳妥,顺便把扣钱的逻辑补上 print(f"You went to the bar, and lost $5, your total loot is : {main.totalLoot - 5}") else: print(roomChoice)
额外优化建议
- 考虑到用户可能输入非数字内容(比如字母、符号),可以加个异常处理避免程序直接崩溃:
try: roomChoice = int(input("Choose 1-3: ")) if roomChoice == 1: print(f"You went to the bar, and lost $5, your total loot is : {main.totalLoot - 5}") elif 2 <= roomChoice <=3: # 这里可以补充其他房间的逻辑 print(f"You chose room {roomChoice}") else: print("Please choose a number between 1-3!") except ValueError: print("Oops, that's not a valid number. Please enter 1, 2, or 3.")
- 原代码里的
+ main.totalLoot如果main.totalLoot是整数类型,会直接触发TypeError,用f-string(如上)或者把数字转成字符串str(main.totalLoot)都能解决这个问题。
内容的提问来源于stack exchange,提问作者Ashley K
相关产品推荐
相关产品推荐

