Ever wanted to compare two values but didn't know which operator might be needed (==, !=, <, >, etc)?
This little function dynamically accepts two values (operands) and a string operator and returns a Boolean result.
Hopefully somebody can use the code below as a starting point. Happy coding!
# Compare Two Values Using String Operator
def Compare(Operand, Operator, Comparitor):
"""
This function allows one to pass two values
: (Operand and Comparitor) and one dynamic string
: Operator. Results (True or False) based on the
: logical evaluation of the full expression.
:
: NOTE: Operand and Comparitor must be the same
: data type.
:
: Incoming Parameters:
: Operand: Any value, any data type
: Operator: "==", "!=", ">", ">=", "<", "<="
: Comparitor: Any value, data type must match
: Operand data type
:
: Return value: True or False (Boolean)
:
: Example: Compare(0, "==", 1) returns False
: Example: Compare("a", "!=", "x") returns True
"""
if type(Operand) != type(Comparitor):
print("Operand and Comparitor must be the same days type:")
print(" Operand data type: ", type(Operand))
print("Comparitor data type: ", type(Comparitor))
raise Exception("Data types mismatch")
#_if
match Operator:
case "==":
if Operand == Comparitor:
return(True)
else:
return(False)
case "!=":
if Operand != Comparitor:
return(True)
else:
return(False)
case ">":
if Operand > Comparitor:
return(True)
else:
return(False)
case ">=":
if Operand >= Comparitor:
return(True)
else:
return(False)
case "<":
if Operand < Comparitor:
return(True)
else:
return(False)
case "<=":
if Operand <= Comparitor:
return(True)
else:
return(False)
case _: # unmatched case above
raise Exception("Operator " + Operator + " not supported.")
raise Exception("Unreachable code error.")
#_def
# Isolated self-tests
if __name__ == "__main__":
print("expect true: ", Compare("phone", "==", "phone"))
print("expect false: ", Compare("phone", "!=", "phone"))
print("expect true: ", Compare("phone", ">", "number"))
print("expect true: ", Compare("phone", ">=", "book"))
print("expect true: ", Compare("phone", "<", "call"))
print("expect false: ", Compare("phone", "<=", "receiver"))
# print("Data type error: ", Compare("x", ">=", 200))
# print("Operand error: ", Compare("phone", "tbd", "telly"))
#_if __name__ Self-Tests