如何在python 2中用随机数写一个数学测验?

时间:2016-06-28 14:10:28

标签: python python-2.7

我目前最好的数学测验是:

answer = ''
while not (answer == '75'):
answer = raw_input('What is 5 x 15?   ')
if answer == '75':
    print ' '
    print 'You are correct' 

    answer1 = ''
    while not (answer1 == '72'):
        answer1 = raw_input('What is 8 x 9?   ')
        if answer1 == '72':
            print ' '
            print 'You are correct'

            answer2 = ' '
            while not (answer2 == '0'):
                answer2 = raw_input('What is 5 x 0?   ')
                if answer2 == '0':
                    print' '
                    print'You are correct'

                    answer3 = ''
                    while not (answer3 == '18'):
                        answer3 = raw_input('what is 6 x 3?   ')
                        if answer3 == '18':
                            print ''
                            print 'You are correct'
                        else:
                            print 'You are incorrect'
                else:
                    print'You are incorrect'
        else:
            print 'You are incorrect'
            continue
else:
    print 'You are incorrect'
    continue

至少对我来说,感觉这段代码太长了,只能回答4个问题。我想知道是否有一种更简单的方法可以使用随机数进行数学测验,因此您不必创建每个问题。

1 个答案:

答案 0 :(得分:1)

您可以像这样动态生成问题:

from random import randint
q = ''
while not q.capitalize() == 'N':
    num1 = randint(0, 100)
    num2 = randint(0, 100)
    answer = input("What is " + str(num1) + " x " + str(num2) + " ? ")
    if answer == (num1 * num2):
        print "Correct"
    else:
        print "Incorrect"

    q = raw_input("Do you want to continue: Y/N? ")

在您的测验中,只有三件事情发生了变化,num1num2因此会发生变化answer。这意味着您可以重复使用其他所有内容并随机生成num1num2