我怎么能改变这个数学测验,以便不使用eval在Python中找到答案?

时间:2015-02-23 19:30:45

标签: python eval

我听说eval因为安全问题而在Python中非常糟糕。 所以我想知道是否有一种方法我不能在这个程序中使用eval

for _ in range(10):
    n1 = random.randint(1, 10)
    n2 = random.randint(1, 10)
    operator = random.choice("+-*")
    question = (n1,operator,n2)
    questionNo +=1
    useranswer = input(question+" = ")
    answer = eval(question)

if useranswer == str(answer):
    correct += 1
    print('Correct!Your score is, ", correct)
else:
    print('Wrong Your score is, ", correct)

1 个答案:

答案 0 :(得分:1)

您可以从运算符的符号到表示该运算符的实际函数进行映射:

import operator as op
operator_map = {"+":op.add, "-":op.sub, "*":op.mul}

然后改为

answer = operator_map[operator](n1, n2)