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

Python If-Else条件语句未返回预期输出问题求解

Python地牢冒险游戏分支逻辑异常修复

错误原因

代码存在两处逻辑问题:

  • 首个门选择的判断条件写法错误:原代码写的if dungeon_door == '1' or '2':在Python中不会被解析为「输入等于1或等于2」。or运算符会分别计算两侧表达式的布尔值,右侧单独的非空字符串'2'布尔判定结果恒为True,因此整个if条件永远成立,无论用户输入什么内容都会直接进入哥布林交互分支,后续的3号门分支、非法输入分支永远无法触发。
  • 哥布林交互段的选项3判断存在类型不匹配:input()获取的用户输入始终是字符串类型,原代码写的elif goblin == 3:是拿字符串和整数3做相等比较,结果永远为False,用户输入'3'时无法触发对应死亡剧情,会误进入非法输入分支。

修复后代码

# write a small adventure game similar to ex31

print("""You enter a dungeon and you find yourself in front of three doors.
Do you go through door #1, door #2 or door #3?""")

dungeon_door = input(">> ")

# 修正条件判断写法,使用in判断值是否在合法选项元组中更简洁
if dungeon_door in ('1', '2'):
    print("You stumble upon a goblin. What do you do?")
    print("1 - Try to kill the goblin with your shoe.")
    print("2 - Try to talk things out.")
    print("3 - Exit through the door you came from.")

    goblin = input(">> ")

    if goblin == '1':
        print("You actually manage to kill the goblin. Dude you're a beast!")

        print("You have to choose between two doors, do you pick the left one or the right one?")

        final_door = input(">> ").lower()

        if final_door == 'left':
            print("This door leads to the treasure chamber. Dungeon cleared, congrats!")
        elif final_door == 'right':
            print("After you open to door an enormous one-eyed monster eats you. This dungeon was too much for you, try again.")
        else:
            print(f"What does {final_door} even mean? You're kicked out of the dungeon, bye.")

    elif goblin == '2':
        print("""Can you speak Ghukliak? Don't think so. The goblin doesn't understand you, you're dead.
        The dungeon was too much for you, bye.""")
    # 修正类型不匹配问题,将整数3改为字符串'3'
    elif goblin == '3':
        print("The door is somehow locked. The goblin takes this chance to kill you. The dungeon was too much for you, bye.")
    else:
        print(f"What does {goblin} even mean? You're kicked out of the dungeon, bye.")

elif dungeon_door == '3':
    print("Well, it's your lucky day. This door leads directly to the treasure chamber. Dungeon cleared, congrats!")
else:
    print(f"What does {dungeon_door} even mean? You're kicked out of the dungeon, bye.")

注:代码中顺便修正了原打印文本里的拼写错误yoursfelf为yourself,不影响核心逻辑。

内容的提问来源于stack exchange,提问作者rumblingThunder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:54:17