assign operator to variable in python?

后端 未结 4 1400
一个人的身影
一个人的身影 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:33

    I know this is a really old thread, but I believe at the time people didn't know about the eval function (Maybe it came with Python 3). So here's an updated answer to the question

    a = input('enter a value')
    b = input('enter a value') 
    op = input('enter an operand')
    expression = a + op + b # simple string concatenation
    result = eval(expression)
    

    If the input is not expected to be valid all the time ast.literal_eval can be used instead. It raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not. Eg. if a, b and op are respectively 5, 10, + then result is 15

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-28 14:40

    You'll need to compare the user's inputted string to your list of operands by hand. There is no analogue of int() here, since operators are keywords in the language and not values.

    Once you've compared that input string to your list of operands and determined the operator that it corresponds to, you can use the Python standard library's operator module to calculate the result of applying the operator to your two operands.

    0 讨论(0)
  • 2020-11-28 14:56

    The operator module http://docs.python.org/library/operator.html exposes functions corresponding to practically all Python operators. You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b).

    0 讨论(0)
提交回复
热议问题