2016-03-08 11 views
-4

它不会告诉你问题是否正确(当它应该),并且它没有按照它在所有问题被问到时所应该做的。它应该在最后说:“你得分”+ str(correctQuestions)+“/ 10个问题。” 下面是代码:Python随机数学公式不起作用

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.") 
+0

这看起来很像一个家庭作业问题。 –

+0

@CalleDybedahl它看起来像家庭问题,我可以提出新的标签'数学测验在python'? – gboffi

回答

0

由于这看起来像一个课外练习你需要一些时间来想想我不会解决这个问题。然而,这里有一些提示:

变量finish始终是False,它永远不会更新,所以它也难怪游戏永远不会完成。对此做些事情。

第二个在if choice==("+"):有可能变量choice不存在(也不是number1number2)。考虑一下你在while循环下放的东西以及你不知道的东西。

此外,您还没有在之前声明它的elif声明中有一个变量realAnswer。由于该变量不存在,如果它被评估,它会给你一个NameError

0

比方说choice*。 Python得到if choice==("+"):。结果是:False,所以它检查elifelif answer==realAnswer:此时realAnswer尚未定义。您在if块中定义了realAnswer,但if块未执行。你需要从每个choice取出elifelse块,而是把他们在最后:

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

而且,你永远无法定义finish,只能作为False。您使用if questionNumber < 10 and questionNumber >= 0:,但是您不说如果questionNumber而不是010之间该怎么办。你需要一个else块,它会跳出循环。