1

I have to perform a certain arithmetic operation between decimal numbers. The operations can be 'add', 'subtract' or 'multiply', and the desired operation will be passed in to our function along with the numbers. The way I want to do this is that I want to store the ASCII values of the operations '+', '-' and '*' and then somehow use that to perform the operation between the two numbers.

def (a, b, op):
  dict{'add':ord('+'), 'subtract':ord('-'), 'multiply':ord('*')}
  return a dict[op] b # this statement does not work

Is there a way to achieve something like that in python ?

I know one alternative is to use:

from operator import add,sub,mul

and then use the imported values in the hash instead, but for this question I am interested in finding out if its possible to do it the way I asked in the original question. Thanks !

comatose
  • 1,952
  • 7
  • 26
  • 42

2 Answers2

1

No, this

a dict[op] b

is not valid Python.

Use the functions from operator.

1

Yes there is an eval() function in python which takes string as input and returns the output , so you slightly need to change the approach, eval() is generally used as :

print eval("2 + 3")
>>> 5

So the new code looks something like :

def evaluate(a, b, op):
    dict = {'add':'+', 'subtract':'-', 'multiply':'*'}
    return eval(str(a)+ dict[op] +str(b))

print evaluate(2,3,"add")
>>> 5
ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • 1
    Be sure to read [Is Using eval In Python A Bad Practice?](http://stackoverflow.com/q/1832940/464709), though. – Frédéric Hamidi Apr 21 '15 at 08:54
  • Yeah I know, But it is the demand of the question , better way would be to use a switch case or some other neat approach but I didn't want to change the intent of the question so made minimal changes to make it work , thanks for the insight, appreciated :) – ZdaR Apr 21 '15 at 08:57