Search code examples
pythonarithmetic-expressions

for in loop arithmetic


operation = ['/','*','+','-']
a =5
b= 2
for op in operation:
    output = a+op+b
    print output

Here the output I get is

5/2
5*2
5+2
5-2

but I want

2.5
10
7
3

What is the way to do it?


Solution

  • The easiest way is to use a dictionary that maps the symbols to functions that perform the operation, which can be found in the operator module.

    import operator
    d = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div }
    operation = d.keys()
    a = 5
    b = 2
    for op in operation:
        output = d[op](a, b)
        print output