为什么我的数学问题不起作用?

时间:2015-01-22 11:34:33

标签: python python-3.x

当我去运行该程序时,它会重复"What is the answer?"

import random
def questions():
    name=input("What is your name: ")
    print("Hello there",name,"!")


    finish = False
    questionnumber = 0
    correctquestions = 0

    while finish == False:
        choice = random.choice("+-x")
        if questionnumber < 10 | questionnumber >= 0:
            number1 = random.randrange(1,10)
            number2 = random.randrange(1,10)
            print((number1),(choice),(number2))

            while True:
                try:
                    answer=int(input("What is the answer?"))
                except ValueError:
                    print("your answer must me a number!")
                    continue
            questionnumber = questionnumber + 1
            if choice==("+"):
                realanswer = number1+number2
            if answer==realanswer:
                print("That's the correct answer")
                correctquestions = correctquestions + 1
            else:
                print("Wrong answer, the answer was",realanswer,"!")

            if choice==("x"):
                realanswer = number1*number2
                if answer==realanswer:  
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")

            if choice==("-"):
                realanswer = number1-number2

                if answer==realanswer:
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")
        finish = True
        print("Good job",name,"! You have finished the quiz")
        print("You scored " + str(correctquestions) + "/10 questions.")
questions()

例如:

What is your name: Will
Hello there Will !
3 x 9
What is the answer?27
What is the answer?27
What is the answer?

2 个答案:

答案 0 :(得分:1)

continue语句无用:无论如何循环都会继续。您需要的是break,如下所示:

    while True:
        try:
            answer = int(input("What is the answer?"))
            break
        except ValueError:
            print("Your answer must be a number!")

另请注意,您的错误消息中有拼写错误:您有me而不是be

答案 1 :(得分:0)

这里有一个无限while循环:

while True:
    try:
        answer=int(input("What is the answer?"))
    except ValueError:
        print("your answer must me a number!")
        continue