Reputation: 79
I hope it's pretty clear what I wanna do with this function:
def this_one_operator(math_operator, num1, num2):
return num1 * num2 if operator == "*" \
or num1 / num2 if operator == "/" \
or num1 + num2 if operator == "+" \
or num1 - num2 if operator == "-"
Obviously, it doesn't work (SyntaxError: invalid syntax).
Sorry if I duplicate the question. I did my best to find here how to deal with that problem. Also, I appreciate any suggestion how to edit the question if it's not accurate.
Thanks.
Upvotes: 2
Views: 81
Reputation: 566
This isn't pretty, but it works:
def this_one_operator(math_operator, num1, num2):
return (operator == "/")*(num1/num2) + \
(operator == "+")*(num1+num2) + \
(operator == "-")*(num1-num2) + \
(operator == "*")*(num1*num2)
The reason this works is that the boolean statements are equal to either 0 or 1, so multiplying them by the correct expression and summing the correct total will yield the right result.
Edit: Actually, this doesn't work as others have pointed out because the division operation may result in an undefined result.
Upvotes: 2
Reputation: 213378
Yes, but it's ugly.
return (x * y if operator == "*" else
x / y if operator == "/" else
x + y if operator == "+" else
x - y if operator == "-" else
None)
Alternatively:
import operator
OPERATORS = {
'*': operator.mul,
'/': operator.truediv,
'+': operator.add,
'-': operator.sub,
}
return OPERATOR[op](x, y)
Upvotes: 2
Reputation: 15310
Python has a value if condition else default
ternary operation, which you could stack for this result. However, it's not very compact, and not very pythonic to be doing what you seem to want to do.
Instead, you might try:
import operator
def binary_op(op, lopd, ropd):
return { '/' : operator.floordiv,
'*' : operator.mul,
'+' : operator.add,
'-' : operator.sub,
'%' : operator.mod }[op](lopd, ropd)
Upvotes: 7