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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:47:00