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