python如何让减价乘除变成变量之后再变回来
天蓬老师
天蓬老师 2017-04-18 10:20:00
0
3
649
a = 1
b = 2
for opt in ["+", "-", "*", "/"]:
    print(aoptb)

如上图所示,当然我的语法是错误的,我想最后输出 3,-1,2,0.5 ,正确的语法应该如何去写

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
小葫芦
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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template