Python break函数不会在true时结束

时间:2012-12-19 22:42:09

标签: python while-loop break

为什么休息时间不会结束,而是回到起点?

while True:
    print('This is a quiz')
    print('What is your name?')
    Name = input()
    print('Hello ' + Name + ', The quiz will now begin')
    import time
    time.sleep(2)
    question1 = "Question one: "
    answer1 = "True" and "true"
    print(question1)
    qanswer = input()

    if qanswer != answer1:
        print('Sorry, the answer is: ' + answer1)
        break

    if answer1 == qanswer:
            print("Correct! Here's the next question")

我对python很新,所以我认为这只是对这些术语的简单滥用。

3 个答案:

答案 0 :(得分:5)

break存在整个while循环。

continue正是您要找的,返回到下一个while次迭代。

您可以在官方文档中详细了解控制流工具breakcontinuehttp://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

(还有一些其他错误正如其他人所说的那样)

答案 1 :(得分:0)

使用“continue”关键字,而不是“break”。

答案 2 :(得分:0)

....
answer1 = ["True", "true"]
...
if not(qanswer in answer1):
    print('Sorry, the answer is: ' + answer1)
    break
else:
   print("Correct! Here's the next question")