我听说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)
答案 0 :(得分:1)
您可以从运算符的符号到表示该运算符的实际函数进行映射:
import operator as op
operator_map = {"+":op.add, "-":op.sub, "*":op.mul}
然后改为
answer = operator_map[operator](n1, n2)