> > num1 = raw_input('Enter the first number: ') > num2 = raw_input('Enter the second number: ') > op = raw_input('Select one of the following [+-*/]: ') > print 'The answer is: ', int(num1), eval(op), int(num2) > ^^^^^^^^ > > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! >
You could eval(num1+op+num2), but it'd be safer to do: import operator operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} fn = operators[op] print "The answer is:", fn(int(num1), int(num2)) Its best to avoid eval when possible :) --S
-- http://mail.python.org/mailman/listinfo/python-list