Python 在回答了10个问题后进行的测验中,如何结束while循环?

Python 在回答了10个问题后进行的测验中,如何结束while循环?,python,random,while-loop,Python,Random,While Loop,您可以通过使用某种变量来解决这个问题,该变量可以跟踪问题的数量。例如:在下面的代码片段中,检查noOfQuestions是否等于或小于10,如果是,则执行while循环,否则不执行 代码: break是您需要的,用于退出循环,或者您可以使用计数器并将while循环中的条件更改为smth,例如:while counter不是10 while True: if play.lower() == "yes": print("great, here we go!")

您可以通过使用某种变量来解决这个问题,该变量可以跟踪问题的数量。例如:在下面的代码片段中,检查noOfQuestions是否等于或小于10,如果是,则执行while循环,否则不执行

代码:


break是您需要的,用于退出循环,或者您可以使用计数器并将while循环中的条件更改为smth,例如:while counter不是10
while True:
    if play.lower() == "yes":
        print("great, here we go!")

        first = random.randint(1, 10)
        second = random.randint(1, 20)

        questionA=input("what is" + str(first) + "+" + str(second))

        userAnswer = first + second

        if userAnswer == userAnswer:
            print("well done")


    elif play.lower() == "no":
        print("ok goodbye")
noOfQuestions = 1
while noOfQuestions<=10: #<-- check if noOfQuestions is less than or equal to 10
    print noOfQuestions
    noOfQuestions += 1 #<--- update the noOfQuestions variable
else:
    print ("noOfQuestions is %d.")%noOfQuestions