Usual method of applying mathematics to variables is
a * b
Is it able to calculate and manipulate two operands like this?
a = input('enter a value') b = input('enter a value') op = raw_input('enter a operand')
Then how do i connect op and two variables a
and b
?
I know I can compare op to +
, -
, %
, $
and then assign and compute....
But can i do something like a op b
, how to tell compiler that op is an operator?
You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b). Show activity on this post. It should be expression = a + c + b .
The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”.
In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.
The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.
You can use the operator module and a dictionary:
import operator ops = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div } op_char = input('enter a operand') op_func = ops[op_char] result = op_func(a, b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With