assign operator to variable in python?

You can use the operator module and a dictionary:

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

Leave a Comment