Mathematical Operators and Dictionaries | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

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

2nd Jan 2019, 10:27 PM
EconPilot
EconPilot - avatar
8 Answers
+ 23
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). https://docs.python.org/3/library/operator.html 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)
2nd Jan 2019, 11:09 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 11
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.
2nd Jan 2019, 10:57 PM
HonFu
HonFu - avatar
+ 2
Hehe, nice. :)
2nd Jan 2019, 11:11 PM
HonFu
HonFu - avatar
+ 1
Function call statement is wrong return (operation_dict(user_input))
27th Feb 2022, 7:44 AM
Jaya
Jaya - avatar
0
you have to put two spaces between order of operation, like -*- -=space
11th Jan 2019, 10:42 AM
Cvbfh
0
Es correcto
11th Dec 2021, 4:35 AM
Edinson.rey4933
Edinson.rey4933 - avatar
- 2
Add + Subtract - Multiply * Divition /
5th Jan 2019, 1:04 PM
Raphael Abban
Raphael Abban - avatar
5th Jan 2019, 1:04 PM
Raphael Abban
Raphael Abban - avatar