Transforming a str to an operator

Xavier Ho contact at xavierho.com
Fri Aug 28 06:50:37 CEST 2009


On Fri, Aug 28, 2009 at 2:35 PM, Ben Finney
<ben+python at benfinney.id.au<ben%2Bpython at benfinney.id.au>
> wrote:

>    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 ({}):".format(','.join(op for op in
> op_funcs))
>
   op_symbol = raw_input(op_prompt)
>    op_func = op_funcs[op_symbol]
>    print 'The answer is: ', op_func(num_1, num_2)


Just fixing the code a little to be more "Pythonic" ;).

Might also want to do exception handling, but with a program this small,
meh.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090828/04de7c5f/attachment.html>


More information about the Python-list mailing list