Transforming a str to an operator

Ben Finney ben+python at benfinney.id.au
Fri Aug 28 06:35:24 CEST 2009


Duke Normandin <dukeofperl at ml1.net> writes:

> Hey....
>
> I'm a Python noob....
>
> So far so good!
>
> I've written the following:
>
> 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!

In general, ‘eval’ on unsanitised input is not the answer.

I would use the following approach:

    import operator

    op_funcs = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.div,
        }

    num_1 = int(raw_input('Enter the first number: '))
    num_2 = int(raw_input('Enter the second number: '))
    op_prompt = (
        "Select an operator "
        + "[" + "".join(s for s in op_funcs.keys()) + "]"
        + ": ")
    op_symbol = raw_input(op_prompt)
    op_func = op_funcs[op_symbol]
    print 'The answer is: ', op_func(num_1, num_2)

This has several advantages:

* The input isn't evaluated directly as code.

* The operator symbols are specified in one place, the ‘op_funcs’
  mapping; if you want to change the set of possible operators, you just
  change it there.

* If the input results in an operator that's not defined, it won't
  attempt to perform it; instead, a simple KeyError will result when
  trying to find the corresponding operator function.

-- 
 \           “I do not believe in immortality of the individual, and I |
  `\        consider ethics to be an exclusively human concern with no |
_o__)  superhuman authority behind it.” —Albert Einstein, letter, 1953 |
Ben Finney



More information about the Python-list mailing list