Iterate through a sequence of operators

杀马特。学长 韩版系。学妹 提交于 2019-12-06 06:23:31

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

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

Try this:

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

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!