assign operator to variable in python?

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

提交回复
热议问题