I have a simple python script that calculates if the price of one variable is less than the other. For example, var1 should always be passed to the calculation function first, and var2 should always be passed second. Then, the function needs to check if var1 is less than var2 Currently, for the calculation function, I have positional parameters, and it is on the end user to correctly pass the parameters in the correct order for the calculation. It seems intuitive enough to know what position to pass each parameter in, but I am wondering if there is a way to safeguard against users being sloppy and passing parameters to the wrong positions?
Example code one:
def get_values():
var_one = 1
print("Var1: ", var_one)
var_two = 2
print("Var2: ", var_two)
print("")
calculate(var_one, var_two)
def calculate(var_one, var_two):
if var_one < var_two:
print("Var1 is less than Var2")
else:
print("Var2 is greater than Var1")
if __name__ == "__main__":
get_values()
Output:
Var1: 1
Var2: 2
Var1 is less than Var2
This is all fine and well. This is the correct way to call the function and it prints logically correct output. However, if I flip the parameter positions in the function call and change the values of var_one and var_two, this happens:
Example Code 2:
def get_values():
var_one = 3
print("Var1: ", var_one)
var_two = 2
print("Var2: ", var_two)
print("")
calculate(var_two, var_one)
def calculate(int_one, int_two):
if int_one < int_two:
print("Var1 is less than Var2")
else:
print("Var2 is greater than Var1")
if __name__ == "__main__":
get_values()
Output:
Var1: 3
Var2: 2
Var1 is less than Var2
As seen here, when var_one is greater than var_two and when we pass the parameters in the wrong position, the output contains a clear logical error. Looking at the code, Var1 is clearly greater than Var2. While it is intuitive how you need to position the parameters here, is there anything that can be done in the calculate() function signature to safeguard against this kind of human/user error, and to ensure var_one always gets passed first to the function before var_two?
***It is important to note that I am using static values here. However, let's say I am pulling in dynamic / changing integers from an API, and I always want to make sure value1 is less than value2, then this needs to be enforced.
5 < 6?