-1

I heard eval was very bad practice in Python because of security issues. So I was wondering if there is a way I could not use eval in this program.

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)
  • http://stackoverflow.com/questions/26260950/how-can-i-randomly-choose-a-maths-operator-and-ask-recurring-maths-questions-wit/26261125#26261125 – Cory Kramer Feb 23 '15 at 19:33
  • this looks amazingly simillar to this earlier question http://stackoverflow.com/questions/28681164/python-questionnaire – Joran Beasley Feb 23 '15 at 19:34
  • note that in this SPECIFIC case, `eval` is not dangerous. `eval` only creates a security concern when you combine it with unsanitized user input. Since completely sanitizing user input is incredibly difficult, it's safe to treat it as a security concern when you combine it with ANY user input. However there's no user input being `eval`'d here. – Adam Smith Mar 04 '15 at 21:57
  • Or I suppose with computer-generated random strings that might end up malicious. The infinite monkey theorem shows that `eval(''.join[random.choice(string.ascii_letters + string.digits + '/\\()\'"[]{};') for _ in range(1000)])` will eventually write a program that will destroy your computer completely. – Adam Smith Mar 04 '15 at 22:02

1 Answers1

1

You could make a mapping from the symbol of the operator to an actual function that represents that operator:

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

then just change to

answer = operator_map[operator](n1, n2)
ely
  • 74,674
  • 34
  • 147
  • 228