a = 1 b = 2 for opt in ["+", "-", "*", "/"]: print(aoptb)
如上图所示,当然我的语法是错误的,我想最后输出 3,-1,2,0.5 ,正确的语法应该如何去写
欢迎选择我的课程,让我们一起见证您的进步~~
a = 1 b = 2 for opt in ["+", "-", "*", "/"]: print(eval(str(a) + opt + str(b)))
python3
>>> import operator as opt >>> optr={'加':opt.add,'减':opt.sub,'乘':opt.mul,'除':opt.truep} >>> a,b=1,2 >>> for k,o in optr.items(): print('%s: %s'%(k,o(a,b))) 乘: 2 加: 3 除: 0.5 减: -1
def add(a, b): return a + b def minus(a, b): return a - b def multiply(a, b): return a * b def pide(a, b): return float(a) / b ops = [add, minus, multiply, pide] for op in ops: print op(1, 2)
python3