while循环中的条件语句不执行其下的所有内容

Conditional statement in while loop not executing everything under it

基本上我正在尝试使用列表创建一种测验。代码是这样的:

foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
             "intermediate cuneiform", "medial cuneiform"]
d = len(foot_bones)
def foot_bones_quiz():
    correct_answers = 0
    answers_left = len(foot_bones)
    guess = input("Enter a bone or q to quit: ")
    while True:        
        if guess.lower() == "q":
            break
        elif guess.lower() in foot_bones:
            print("We got a match on index ",foot_bones.index(guess.lower()))
            #Removes the previous guess from the list to ensure the user can't answer the same thing again
            foot_bones.remove(guess.lower())
            guess = ("Enter a bone or q to quit: ")
            correct_answers += 1
            answers_left -= 1
        else:
            answers_left -= 1
            guess = input("No match. Please try again. You have %s tries left. Enter q to quit"%answers_left)

        if answers_left == 0:
            break
    print("You have %s correct answers out of %s."%(correct_answers,d)

foot_bones_quiz()

当我输入 "calcaneus" 时,我希望代码执行 elif 语句下的所有内容。最终发生的事情是在它打印 "We got a match on index blah" 之后,在 else 语句下打印 "No match" 东西。

我的代码有什么问题?

我觉得你的elif下面的guess应该是:

guess = input("Enter a bone or q to quit: ")

而不是:

guess = ("Enter a bone or q to quit: ")

这是怎么回事,你已经输入了你的第一块骨头,这导致你的代码到达这里:

        print("We got a match on index ",foot_bones.index(guess.lower()))
        #Removes the previous guess from the list to ensure the user can't answer the same thing again
        foot_bones.remove(guess.lower())
        guess = ("Enter a bone or q to quit: ")
        correct_answers += 1
        answers_left -= 1

执行此块。请注意,guess 设置为值 "enter a bone or q to quit: "。你不是在要求输入。

现在猜测是 "enter a bone or q to quit: ",我们到达循环的末尾并重新启动它。

由于 guess.lower() 不在 foot_bones 中,也不在 "q" 中,因此您最终会进入 else 语句。