Python v3.3.5数学问题程序

时间:2014-11-11 10:23:18

标签: python-3.x

有人知道分数计数器为什么不在这个程序中工作?该程序旨在运行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))

1 个答案:

答案 0 :(得分:0)

存在一些问题:

  • 您忘记更改if语句中的数字。
  • 您必须将答案的输入解析为int,因为input返回一个字符串。
  • score == score+1是一个比较,它总是返回false。它应该是“=”。 score = score + 1或更短的score += 1完全相同
  • 2 ifs只嵌套一件事可以写在同一个if语句中。

你写了这个:

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表示回车。

你应该做一些更改,以防止用户在答案中写其他字符,但我认为你已经有足够的工作来处理这个问题了。