+ 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])
8 ответов
+ 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)
+ 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.
+ 2
Hehe, nice. :)
+ 1
Function call statement is wrong
return (operation_dict(user_input))
0
you have to put two spaces between order of operation, like -*- -=space
0
Es correcto
- 2
Add +
Subtract -
Multiply *
Divition /