assign operator to variable in python?

后端 未结 4 1409
一个人的身影
一个人的身影 2020-11-28 14:23

Usual method of applying mathematics to variables is

a * b

Is it able to calculate and manipulate two operands like this?

         


        
4条回答
  •  [愿得一人]
    2020-11-28 14:35

    You can use the operator module and a dictionary:

    import operator
    ops = {
        "+": operator.add,
        "-": operator.sub,
        "*": operator.mul,
        "/": operator.div
    }   
    op_char = input('enter a operand')
    op_func = ops[op_char]
    result = op_func(a, b)
    

提交回复
热议问题