Python随机数学方程不起作用

时间:2016-03-08 10:37:08

标签: python random

它不会告诉你问题是否正确(何时应该),并且当问到所有问题时它没有做到它应该做的事情。它应该在结尾说:“你得分”+ str(correctQuestions)+“/ 10个问题。” 这是代码:

import random

name = input("What is your name: ")

finish = False
questionNumber = 0
correctQuestions = 0

while finish == False: 
    op = ['+','-','*']
    choice = random.choice(op)
    if questionNumber < 10 and questionNumber >= 0:
        number1 = random.randrange(1,10)
        number2 = random.randrange(1,10)
        print((number1),(choice),(number2))
        answer=int(input("What is the answer?"))
        questionNumber = questionNumber + 1

if choice==("+"):
    realAnswer = number1+number2
elif answer==realAnswer:
    print("That's the correct answer")
    correctQuestions = correctQuestions + 1
else:
    print("Wrong answer")

if choice==("*"):
    realAnswer = number1*number2
elif answer==realAnswer:
    print("That's the correct answer")
    correctQuestions = correctQuestions + 1
else:
    print("Wrong answer")

if choice==("-"):
    realAnswer = number1-number2
elif answer==realAnswer:
    print("That's the correct answer")
    correctQuestions = correctQuestions + 1
else:
    print("Wrong answer")

if finish == True:
    print("You scored " + str(correctQuestions) + "/10 questions.")

2 个答案:

答案 0 :(得分:0)

由于这看起来像是一项家庭作业,我不会解决它,因为你需要一些时间来思考它。不过这里有一些提示:

变量finish总是False,它永远不会更新,所以难怪游戏永远不会完成。做点什么。

if choice==("+"):行后,变量choice可能不存在(也不是number1number2)。想想你放在while循环下的内容以及你不知道的内容。

realAnswer语句中还有一个变量elif,而您之前没有声明它。由于变量甚至不存在,如果它被评估,它将给你一个NameError

答案 1 :(得分:0)

我们说choice*。 Python到达if choice==("+"):。结果:False,因此检查elifelif answer==realAnswer:此时realAnswer尚未定义。您在realAnswer块中定义if,但if块未执行。您需要从每个elif中取出elsechoice块,然后将它们放在最后:

if answer == realAnswer:
    print("That's the correct answer")
    correctQuestions = correctQuestions + 1
else:
    print("Wrong answer")

此外,除了finish之外,您永远不会将False定义为任何内容。您使用的是if questionNumber < 10 and questionNumber >= 0:,但如果在questionNumber0之间10 ,您就无法说明该怎么做。你需要一个else块来突破循环。