doing "right" is something that depends on how much functionality you want, and it’s something that, if you want to read parentheses for example, can get really complicated.
But to keep it simple, let’s assume that the input expressions are always number, operator, number and everything separated by spaces - and let’s also let Python itself process the numeric operands to give their value as a floating number. (that is, let’s call the built-in "float" instead of processing the input digit by digit to build the operands)
So we just focus on the operator itself - and we can create a simple dictionary that maps the operator symbol to a function that takes two parameters. To get even shorter, we can use the keyword lambda
which allows the definition of simple functions as expressions within the dictionary body itself.
Then you can do something like this:
operadores = {
"+": lambda op1, op2: op1 + op2,
"-": lambda op1, op2: op1 - op2,
"*": lambda op1, op2: op1 * op2,
"/": lambda op1, op2: op1 / op2
}
def process(expression):
op1, operator, op2 =expression.split()
op1 = float(op1)
op2 = float(op2)
return operadores[operator](op1, op2)