I'd like to pass a math operator, along with the numeric values to compare, to a function. Here is my broken code:
def get_truth(inp,relate,cut): if inp print(relate) cut: return True else: return False
and call it with
get_truth(1.0,'>',0.0)
which should return True.
Python pass StatementThe pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
Python is operator vs == operator The equality operator ( == ) compares two variables for equality and returns True if they are equal. Otherwise, it returns False . Since a and b references the same object, they're both identical and equal. In the following example, both lists have the same elements, so they're equal.
Have a look at the operator module:
import operator get_truth(1.0, operator.gt, 0.0) ... def get_truth(inp, relate, cut): return relate(inp, cut) # you don't actually need an if statement here
Make a mapping of strings and operator functions. Also, you don't need if/else condition:
import operator def get_truth(inp, relate, cut): ops = {'>': operator.gt, '<': operator.lt, '>=': operator.ge, '<=': operator.le, '==': operator.eq} return ops[relate](inp, cut) print(get_truth(1.0, '>', 0.0)) # prints True print(get_truth(1.0, '<', 0.0)) # prints False print(get_truth(1.0, '>=', 0.0)) # prints True print(get_truth(1.0, '<=', 0.0)) # prints False print(get_truth(1.0, '==', 0.0)) # prints False
FYI, eval()
is evil: Why is using 'eval' a bad practice?
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