我要如何更改此数学测验才能不使用 eval 在 Python 中找到答案?

How could I change this Maths quiz in order to not use eval to find the answer in Python?

我听说 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)

您可以将运算符的符号映射到代表该运算符的实际函数:

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

那就改成

answer = operator_map[operator](n1, n2)