找到检查特定算术答案是否正确的内容

时间:2015-01-15 21:04:24

标签: python function if-statement while-loop eval

我想知道是否有一个命令可以解决您提出的数学问题并将其与用户编写的答案进行比较?显然,如果它错了,它将输出错误,如果它是对的,那就是正确的。这是我的代码:

import time
person=input('Hello there, what is your name? ')
print('Hello',person,'today you will test a maths quiz which is 10 questions')
time.sleep(1)
print('Good luck here is your first question:')
UserScore=0
UserWrong=0
x=0
while x<10:
    import random
    Ran=random.randint(1, 10) 
    dom=random.randint(1, 10)
    Operators=[ 'plus', 'minus', 'times']
    op = random.choice(Operators)
    AnswerOne=input('What is '+str(Ran) +' '+str(op) +' '+str(dom) +'? ')
    if int(AnswerOne) == Ran + dom:
        print('Correct!')
        UserScore= UserScore + 1
    elif int(AnswerOne) == Ran - dom:
        print('Correct!')
        UserScore= UserScore + 1
    elif int(AnswerOne) == Ran * dom:
        print('Correct!')
       UserScore= UserScore + 1
    else:
        print('You are wrong! Better look next time :D')
        UserWrong= UserWrong +1
    x=x+1
print('You got '+str(UserScore) +' right and '+str(UserWrong) +' wrong')

2 个答案:

答案 0 :(得分:1)

您正在做的事情是可行的,您只需要稍微调整一下条件。你现在正在说“如果用户的答案是+ b,那么它是正确的” - 即使问题是“什么时候是b”。因此,您还需要检查操作是否匹配。你可以这样做:

if answer == ran+dom and op == 'plus':
     # correct

与其他操作类似。

您还可以通过使用字典而不是操作列表来简化它 - 键将是当前字符串,值是执行正确操作的函数,例如运算符模块中的值,这样:

operations = { "plus": operator.add, 
               "times": operator.mul,
               "minus": operator.sub
             }

这使您可以简化为一个条件 - 您可以从字典中提取相应的检查功能,并测试它是否给出了与用户相同的答案:

if operations[op](ran, dom) == answer:
    # correct

这涵盖了所有三个分支,您决定稍后再添加。

答案 1 :(得分:-2)

编辑:好的,我把它切成了一点。

我有一个Question基类和四个子类:乘法,除法,加法和减法。

每次创建一个Question对象时,它都会使用随机值初始化自己。然后,您可以请求问题字符串和相关的答案值​​。

from random import choice, randint

class Question:     # base class
    def __init__(self, difficulty=20):
        self.a = randint(1, difficulty)
        self.b = randint(1, difficulty)
    def question(self):
        raise NotImplemented
    def answer(self):
        raise NotImplemented

class Multiplication(Question):
    def question(self):
        return "What is {} * {}? ".format(self.a, self.b)
    def answer(self):
        return self.a * self.b

class Division(Question):
    def question(self):
        # invert the question to ensure a nice answer value
        return "What is {} / {}? ".format(self.a * self.b, self.a)
    def answer(self):
        return self.b

class Addition(Question):
    def question(self):
        return "What is {} + {}? ".format(self.a, self.b)
    def answer(self):
        return self.a + self.b

class Subtraction(Question):
    def question(self):
        # invert the question to ensure a nice answer value
        return "What is {} - {}? ".format(self.a + self.b, self.a)
    def answer(self):
        return self.b

然后我使用这些类来实现一个询问问题并标记结果的函数,

def do_question(qtypes=[Multiplication, Division, Addition, Subtraction]):
    # pick a random question-type
    #   and create a question of that type
    q = choice(qtypes)()
    # prompt user for their answer
    guess = get_int(q.question())
    # mark their answer
    if guess == q.answer():
        print("Correct!")
        return True
    else:
        print("Sorry, the right answer was {}".format(q.answer()))
        return False

和一个询问一定数量的问题并返回总分的函数,

def do_quiz(num_questions=10):
    return sum(do_question() for i in range(1, num_questions + 1))
然后我们给出一个测验并显示结果:

def main():
    correct = do_quiz()
    print("\nYou solved {} of 10 questions".format(correct))

if __name__ == "__main__":
    main()

并且,在运行时,它看起来像

What is 8 * 2? 16
Correct!

What is 1 + 3? 4
Correct!

What is 27 - 12? 15
Correct!

What is 17 + 1? 19
Sorry, the right answer was 18

What is 4 / 1? 4
Correct!

What is 19 - 14? 5
Correct!

What is 36 / 3? 12
Correct!

What is 12 * 7? 84
Correct!

What is 48 / 4? 12
Correct!

What is 26 - 8? 18
Correct!

You solved 9 of 10 questions