While循环无限循环(2.7)

2024-03-28 16:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在对Python还很陌生,只是有点头绪。你知道吗

我一直在做一个多选测验,似乎随着我的每一次进步,出现的问题就越多。这是测验本身的一个小插曲。问题是,每当我运行这段代码时,while循环会继续重复,并且不会转到下一节q2。你知道吗

def q1(name):
    print
    q1= int(raw_input(
        """Question #1
Which of the following animals is native to New Zealand?
1) Possum
2) Rat
3) Tuatara
4) Sheep
Please enter your answer (1, 2, 3, 4)"""))
    while q1 not in ["1", "2", "3", "4"]:
        q1 = int(raw_input("choose 1, 2, 3 or 4."))

        if q1 == 1 :
            print
            print"That is an incorrect answer. The possum is a native species of Australia."
            W_A()
        elif q1 == 2 :
            print
            print"That is an incorrect answer. The rat arrived on ships, assumedly along with first human inhabitants of New Zealand."
            W_A()
        elif q1 == 3 :
            print
            print'Well done',name.title(),'. That is the correct answer. The tuatara is endemic to New Zealand, and due to its close relation to the dinosaurs that roamed millions of years ago, they are sometimes referred to as a "Living fossil".'
            R_A()
        elif q1 == 4 :
            print
            print 'That is an incorrect answer. Sheep arrived with immigrants from Europe in the 1800s for agricultural purposes. They were used to provide wool and meat for farmers.'
            W_A()

我很想知道为什么会发生这种情况,以及一个简单的解决办法是什么。非常感谢您的帮助!你知道吗


Tags: ofthetoanswerannewthatis
1条回答
网友
1楼 · 发布于 2024-03-28 16:22:43

您的q1变量是一个整数,但是您将它与条件中的字符串进行比较。永远不会是True。你知道吗

>>> 1 == "1"
False

while q1 not in [1, 2, 3, 4]:替换您的条件。你知道吗

相关问题 更多 >