Heim > Fragen und Antworten > Hauptteil
a = 1
b = 2
for opt in ["+", "-", "*", "/"]:
print(aoptb)
如上图所示,当然我的语法是错误的,我想最后输出 3,-1,2,0.5 ,正确的语法应该如何去写
高洛峰2017-04-18 10:22:00
a = 1
b = 2
for opt in ["+", "-", "*", "/"]:
print(eval(str(a) + opt + str(b)))
迷茫2017-04-18 10:22:00
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
PHP中文网2017-04-18 10:22:00
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)