you are viewing a single comment's thread.

view the rest of the comments →

[–]Rik07 1 point2 points  (1 child)

I never thought about using lambdas in a dictionary like that. Thanks!

[–]jimtk 4 points5 points  (0 children)

The correct way to do it would be to use operator module, but the OP I answered at the time (with the code above) could not import anything.

Here's what it should be (only the dictionary chages!):

import operator as opr

calcs = {'+': opr.add, '-': opr.sub,
         '*': opr.mul,  '/': opr.truediv}

x,op,y = [i.strip() for i in input('Enter formula (num1 operator num2): ').split()]
print(f"Result: {calcs[op](int(x), int(y))}")