3

Is it possible/Is there a way to iterate through a sequence of operators as in the following example?

a, b = 5, 7
for op in (+, -, *, /):
    print(a, str(op), b, a op b)

One possible use case is the test of the implementation of various operators on some abstract data type where these operators are overloaded.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
green diod
  • 1,399
  • 3
  • 14
  • 29

3 Answers3

7

You can use the operator module.

for op in [('+', operator.add), ('-', operator.sub), ('*', operator.mul), ('/', operator.div)]:
    print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

You can create your own operations, then iterate through them.

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

def mult(a, b):
    return a * b

def div(a, b):
    return a / b
a, b = 5, 7

operations = {'+': add,'-': sub, '*':mult, '/': div}
for op in operations:
    print(a, op, b, operations[op](a, b))
Kenly
  • 24,317
  • 7
  • 44
  • 60
  • 1
    http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice – Remi Guan Dec 16 '15 at 13:16
  • 2
    The eval approach was more straightforward for simple (binary infix) operations and avoided defining all those functions. Now,when the operations are more complex of course, I can't avoid that. Acknowledged the 'avoid eval' part. – green diod Dec 16 '15 at 13:50
  • @zetysz: Yeah :), about `eval`, it's really dangerous. So don't use it ***forever***. – Remi Guan Dec 16 '15 at 13:58
  • 1
    @KevinGuan In the use case I mentioned above, namely for testing purpose, eval would only be confined in the test code. But still, if it can be avoided, let's avoid it. – green diod Dec 16 '15 at 14:08
0

Try this:

a,b=5,7
for op in ['+','-','*','/']:
    exec 'print a' + op + 'b'

Hope this helps!