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

Python中else语句失效,非法输入错误触发分支求助

问题修复:输入任意内容均触发第一个分支的bug

问题根源

你的代码存在两个关键逻辑错误:

  1. or运算符使用错误:if cmd == "yes" or "y"这种写法不符合Python语法逻辑。因为"y"是一个非空字符串,在布尔判断中会被视为True,所以这个条件永远成立,不管用户输入什么,都会直接进入第一个分支。同理,starting_room函数里的方向判断也犯了同样的错误。
  2. 未处理非法输入的分支:外层if cmd in yes_no:只处理了合法输入的情况,但当用户输入不在yes_no列表中的内容时,没有对应的分支来打印错误提示。

修复步骤

  1. 修正or的条件写法:

    • 将if cmd == "yes" or "y"改为if cmd in ["yes", "y"](或完整的if cmd == "yes" or cmd == "y")
    • 同理,把elif cmd == "no" or "n"改为elif cmd in ["no", "n"]
    • starting_room函数里的方向判断也做同样修改,比如if cmd in ["north", "n"]
  2. 补充非法输入的处理分支:

    • 在start函数的外层if语句后添加else分支,用来打印else_msg,处理用户输入不在yes_no中的情况。

修复后的完整代码

import time

yes_no = ['yes', 'y', 'no', 'n']
directions = ['north', 'n', 'south', 's', 'east', 'e', 'west', 'w']
else_msg = "Invalid command"


def start():
    print("-------------------------------")
    print("Welcome to Haunted Funhouse")
    print("Do you want to proceed? (y/n)")
    cmd = input(">")
    if cmd in yes_no:
        if cmd in ["yes", "y"]:
            time.sleep(1)
            print("\n------------------")
            print("Get ready")
            print("--------------------\n")
            starting_room()
        elif cmd in ["no", "n"]:
            time.sleep(1)
            print("Okay, shutting down")
            quit()
    else:
        print(else_msg)


def starting_room():
    print("-----------Start-----------")
    print("You stand in a octagon room")
    print(
        "There are windows to the northwest, northeast, southeast, southwest")
    print("There are doors to the:\n- North\n- South\n- East\n- West")
    print("---------------------------------------------------------")
    print("Where do you want to go? (n/s/e/w)")
    cmd = input(">")
    if cmd in directions:
        if cmd in ["north", "n"]:
            time.sleep(1)
            print("You enter through the north door")
        elif cmd in ["south", "s"]:
            time.sleep(1)
            print("You go through the south door")
        elif cmd in ["west", "w"]:
            time.sleep(1)
            print("You enter through the west door")
        elif cmd in ["east", "e"]:
            time.sleep(1)
            print("You enter through the east door")
    else:
        print(else_msg)


start()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:36:20