有人知道分数计数器为什么不在这个程序中工作?该程序旨在运行10个随机数学问题,然后显示分数。但是,虽然它会询问问题,但它始终会将分数显示为' 0'
name = input('Type in your name')
questioncount = 0
score = 0
import random
for questioncount in range(0,10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.randrange(1,4)
if (sign) == 1 :
print('{}x{}'.format(number1, number2))
elif (sign) == 2 :
print ('{}+{}'.format(number1, number2))
elif (sign) == 3 :
print ('{}-{}'.format(number1, number2))
answer = input('What is the answer?')
if (sign) == 1:
if (answer) == number1*number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1+number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1-number2:
score == score+1
else:
pass
pass
print('you got {} answers right!'.format(score))
答案 0 :(得分:0)
存在一些问题:
score == score+1
是一个比较,它总是返回false。它应该是“=”。 score = score + 1
或更短的score += 1
完全相同你写了这个:
if (sign) == 2:
if (answer) == number1+number2:
score += 1
else:
pass
可能是:
if (sign) == 2 and (answer) == number1+number2:
score += 1
if/elif
语句而不是else:pass
这样
if (sign) == 1 and (answer) == number1*number2:
score += 1
elif (sign) == 2 and (answer) == number1+number2:
score += 1
elif (sign) == 3 and (answer) == number1-number2:
score += 1
甚至更好
if (sign == 1 and answer == number1 * number2) or (sign == 2 and answer == number1 + number2) or (sign == 3 and answer == number1 - number2) :
score += 1
那就是说,我会这样编写这个程序:
import random
name = input('Type in your name\n')
score = 0
for _ in range(10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.choice(["*", "+", "-"])
expression = "{0} {1} {2}".format(number1,sign,number2)
print(expression)
answer = int(input('What is the answer?\n'))
print("-------------")
if answer == eval(expression):
score += 1
print('{}, you got {} right answers!'.format(name, score))
注意:
使用_
因为它并不重要。你可以随意调用它,你甚至不必在之前声明它。
\n
表示回车。
你应该做一些更改,以防止用户在答案中写其他字符,但我认为你已经有足够的工作来处理这个问题了。