为什么忽略elif语句

时间:2020-07-12 14:13:04

标签: python

我正在编写一个程序,作为if-elif-else语句的练习,并且可以提供一些关于为什么elif语句未运行的建议。

我想提供选择为库存清点岩石的选项。 那行得通,但是如果我说我不想拾起石头,那条elif语句似乎被忽略了,我拾起了石头并将它们添加到我的库存中。

我没有任何实际错误,但是看不到为什么没有激活elif语句。作为本练习的一部分,我在同一程序中多次使用了此命令,而没有遇到这个连续的问题。

这些似乎是我遇到的问题:

elif num >=2 and rocks_there == True:
        print("""You keep within touching distance of the castle wall.
                You come across some rocks. Do you want to pick them up.""")
        take = input("> ").lower()

        if "yes" or "y" in take:
            print("You pick up the rocks.")
            inventory.append('Rocks')
            rocks_there = False
            print("You follow the castle walls around to the front of the castle again.")
            grounds()

        elif "no" or "n" in take:
            inventory = inventory
            rocks_there = True
            print("You leave the rocks on the path.")
            print("You follow the castle walls around to the front of the castle.")
            grounds()

以下是整个功能:

def fog(): 全球库存 全球岩石 print(“当浓雾开始在你周围旋转时,你沿着城堡的左边走。”) 打印(“您要继续走还是回到庭院?”)

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

if "back" in choice:
    grounds()

elif "carry" in choice:
    
    num = random.randint(0,10)
    if num < 2:
        print("""The fog envelopes you until you have no idea where you are and can see nothing else.
                Suddenly you feel yourself fall as you step over the edge of a towering cliff.
                You die, but at least you are not undead.""")
        exit(0)
    elif num >=2 and rocks_there == True:
        print("""You keep within touching distance of the castle wall.
                You come across some rocks. Do you want to pick them up.""")
        take = input("> ").lower()

        if "yes" or "y" in take:
            print("You pick up the rocks.")
            inventory.append('Rocks')
            rocks_there = False
            print("You follow the castle walls around to the front of the castle again.")
            grounds()

        elif "no" or "n" in take:
            inventory = inventory
            rocks_there = True
            print("You leave the rocks on the path.")
            print("You follow the castle walls around to the front of the castle.")
            grounds()

    elif num >= 2 and rocks_there == False:
        print("You follow the castle walls around to the front of the castle.")
else:
    print("The fog has scrambled your brain and I do not understand you.")
    print("I hope you find your way out.")
    print("Goodbye!")
    exit(0)
    

1 个答案:

答案 0 :(得分:1)

如果您尝试使用此简单代码

mylist = []
if "yes" or "y" in mylist:
    print("oops")

您会看到代码被解释为

mylist = []
if "yes" or ("y" in mylist):
    print("oops")

从此

if "yes":
    print("oops")

它将始终贯穿if部分,而永远不会贯穿elif部分。这是因为“是”被认为是truthy value

您可能想要的是

if take in ["y", "yes"]:

是“检查用户输入(take)是否在可能答案的列表([])中”。语句的 no 部分与此类似。