【问题标题】:My else statement doesn't work. What is wrong? [duplicate]我的 else 语句不起作用。怎么了? [复制]
【发布时间】:2022-11-18 16:08:42
【问题描述】:

所以在 if 语句中,如果玩家没有输入正确的内容,我想打印一条消息。问题是当我启动代码并随机输入一些东西时,如果它检查是并继续前进,它会跳到第一个。它甚至为我回复了下一个功能。有没有办法来解决这个问题?

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 == "yes" or "y":
            time.sleep(1)
            print("\n------------------")
            print("Get ready")
            print("--------------------\n")
            starting_room()
        elif cmd == "no" or "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 == "north" or "n":
            time.sleep(1)
            print("You enter through the north door")
        elif cmd == "south" or "s":
            time.sleep(1)
            print("You go through the south door")
        elif cmd == "west" or "w":
            time.sleep(1)
            print("You enter through the west door")
        elif cmd == "east" or "e":
            time.sleep(1)
            print("You enter through the east door")
        else:
            print(else_msg)


start()

我试过将“如果 cmd 不在 yes_no”中更改为“如果 cmd 在 yes_no 中”,但它没有用。我通过 Thonny 运行它,代码检查器说没问题

【问题讨论】:

    标签: python


    【解决方案1】:

    更改如下:

    if cmd in yes_no:
        if cmd == "yes" or cmd == "y":
            time.sleep(1)
            print("
    ------------------")
            print("Get ready")
            print("--------------------
    ")
            starting_room()
        elif cmd == "no" or cmd == "n":
            time.sleep(1)
            print("Okay, shutting down")
            quit()
    

    【讨论】:

      【解决方案2】:

      你需要改变:

      if cmd == "yes" or "y"
      

      if cmd == "yes" or cmd == "y"
      

      ..在代码的其他部分也类似。

      如果 cmd == 'no' 则此测试将为真,因为非空字符串为真。

      另一种构造可能是:

      if cmd in {'yes', 'y'}
      

      【讨论】:

        猜你喜欢
        • 2022-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-05
        • 1970-01-01
        • 1970-01-01
        • 2012-02-09
        相关资源
        最近更新 更多