Mathematical Operators and Dictionaries | SoloLearn: Learn to code for FREE!


Mathematical Operators and Dictionaries

I am attempting to make a calculator. To accomplish this, I wanted to take a user input (add, subtract, multiply, divide) and assign it a value, in this case a mathematical operator. It appears that Python doesn't like assigning an operator as a value to a key in a dictionary. Did I make a mistake? Here is the code: def operation_user_performes(user_input): operation_dict = { "add" : +, "subtract" : -, "multiply" : *, "divide" : /, } return (operation_dict[user_input])

1/2/2019 10:27:16 PM


6 Answers

New Answer


Aside from what HonFu said, you could also use the functional versions of the operators. So to get 2 + 3, you could do operator.add(2, 3). So the code will have from operator import add, sub, mul, truediv Then operation_dic = {"add": add, "subtract": sub, "multiply": mul, "divide": truediv} And to get the result of the calculation, something like operation_user_performs(user_input)(operand1, operand2)


Yeah, you can't do that. What you can do is write the operators in string format like '+'. I assume you want to take user input for the operands too? You can tie them to a single string and evaluate it as code, pattern being: eval('5'+'+'+'7') You can also put a function name as a value and execute it by dict access... but defining functions for basic arithmetic operations just for this looks like overkill.


Hehe, nice. :)


Add + Subtract - Multiply * Divition /


you have to put two spaces between order of operation, like -*- -=space