基本上,我正在尝试使用列表来创建测验。代码如下:
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语句下的所有内容。最终发生的是在它打印出“我们在索引上有一个匹配项”之后,在“ else”语句下打印出“没有匹配项”。
我的代码怎么了?
答案 0 :(得分:1)
我认为您guess
下的elif
应该是:
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
语句。