-1
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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    `output = eval(str(float(a)) + op + str(float(b)))` – Jakob Oct 29 '14 at 12:14
  • 1
    Why on earth would you expect e.g. `"5" + "/" + "2"` to be `2.5`? It's just a string, it won't be magically evaluated as a calculation (not to mention that, in Python 2.x, that calculation evaluates to `2`). – jonrsharpe Oct 29 '14 at 12:16

3 Answers3

1

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
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Use the operator module:

a, b = 5, 2
for op in (operator.div, operator.mul, operator.add, operator.sub):
    print(op(a, b))
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

For this you can use the eval function:

print eval(output)

Note: eval evaluates anything in the string, even if its dangerous. Also, as you know your operators in advance, you can use the operators module:

import operators
operation = [operators.div, operators.mul, operators.add, operators.sub]
a = 5
b = 2
for op in operation:
    output = op(a, b)
    print output
matsjoyce
  • 5,744
  • 6
  • 31
  • 38