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

+5

# 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

HeartattackPilot

+11

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)

+6

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.

+2

Hehe, nice. :)

0

Add + Subtract - Multiply * Divition /

0

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

-4

https://code.sololearn.com/W4Ty57fq5zId/?ref=app