如何用python 2编写随机数的数学测验?
我目前最好的数学测验是:如何用python 2编写随机数的数学测验?,python,python-2.7,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?
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个问题需要回答。我想知道是否有一种更简单的方法来进行随机数字的数学测验,这样您就不必创建每个问题。您可以像这样动态生成问题:
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? ")
在你的测验中,只有三件事发生了变化,它们是
num1
和num2
,结果是答案发生了变化。这意味着您可以重用所有其他内容,并随机生成num1
和num2
如果这是您认为可以改进的工作代码,请参阅。你绝对可以简化它,绝对可以生成随机问题。你显然在学习,所以在这里给你答案可能弊大于利。因此,我想指出一个方向:为什么不列出问题和答案呢?@tomasz plaskota给你的提示是解决这一问题的关键。我还特别问了如何解决这个问题,我已经看到了解决这个问题的代码,但它是除python 2之外的其他语言的代码-忘了在我的问题中提到这一点…首先,理解其他代码在做什么。然后,将该逻辑转换为Python。如果你对某个特定的翻译点有具体的问题,那就在这里。