Transforming a str to an operator

Stephen Hansen apt.shansen at gmail.com
Fri Aug 28 00:32:55 EDT 2009


>
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090827/57bf38e7/attachment-0001.html>


More information about the Python-list mailing list