pythoncompiler-constructionoperators

assign operator to variable in python?


Usual method of applying mathematics to variables is

a * b

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

a = input('enter a value')
b = input('enter a value') 
op = raw_input('enter a operand')

Then how do i connect op and two variables a and b?
I know I can compare op to +, -, %, $ and then assign and compute....

But can i do something like a op b, how to tell compiler that op is an operator?


Solution

  • 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)