我试图构建一个程序,它将整数n作为输入,然后询问n个单位数的加法问题。要添加的数字应从范围[0,9]中随机选择(即0到9,包括0和9)。用户将在提示时输入答案。该函数应该打印“正确”以获得正确答案,并且“不正确”表示错误答案。在n个问题之后,该函数应该打印正确答案的数量。
>>>add(2)
8 + 2 =
Enter answer: 10
correct.
8 + 4 =
Enter answer: 5
Incorrect.
You got 1 correct answer out of 2
到目前为止我得到的代码是:
import random
def game(n):
dig1 = random.randrange(0,10)
dig2 = random.randrange(0,10)
for i in range(n):
print (dig1, '+', dig2, '=')
answer = eval(input('Enter Answer: '))
if answer == dig1 + dig2:
print ('Correct.')
else:
print ('Incorrect.')
答案 0 :(得分:0)
您需要在每个循环中创建 new 随机数字:
def game(n):
for i in range(n):
dig1 = random.randrange(0,10)
dig2 = random.randrange(0,10)
print (dig1, '+', dig2, '=')
answer = eval(input('Enter Answer: '))
if answer == dig1 + dig2:
print ('Correct.')
else:
print ('Incorrect.')
答案 1 :(得分:0)
我添加了请求的统计逻辑并修复了与Martijn指出的相同的循环问题
import random
def game(n):
rights = 0
for z in xrange(n):
dig1 = random.randrange(0,10)
dig2 = random.randrange(0,10)
print (dig1, '+', dig2, '=')
answer = input ('Enter Answer: ')
if answer == dig1 + dig2:
print ('Correct')
else:
rights += 1
print ('Incorrect')
print "You got {rights} right in {n} tries".format(rights=rights, n=n)