search

Home  >  Q&A  >  body text

python如何让减价乘除变成变量之后再变回来

a = 1
b = 2
for opt in ["+", "-", "*", "/"]:
    print(aoptb)

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

天蓬老师天蓬老师2781 days ago631

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:22:00

    a = 1
    b = 2
    for opt in ["+", "-", "*", "/"]:
        print(eval(str(a) + opt + str(b)))

    reply
    0
  • 迷茫

    迷茫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

    reply
    0
  • PHP中文网

    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)

    reply
    0
  • Cancelreply