Say I have two variables:
foo1 = 2
foo2 = x # Actual value unknown
foo1
will always be the same (2
) but foo2
can take any integer value from x
.
Now say I want to compare foo1
to foo2
(find out if it is smaller, bigger or the same size). I could use ==
to test if they are the same value:
foo1 == foo2 # False
So foo1
does not equal foo2
.
Next I see if foo1
is larger with >
:
foo1 > foo2 # False
So we now know that foo1
is smaller than foo2
.
This can be put into a convenient function to compare values:
def cmp(arg1, arg2):
if arg1 == arg2:
return 0
elif arg1 > arg2:
return 1
elif arg1 < arg2:
return -1
print(cmp(2, 3))
Where:
0
means the same size1
means greater than-1
means smaller than
Interestingly Perl has this inbuilt, the <=>
(compareson) operator:
my $foo1 = 2;
my $foo2 = $x;
$foo1 <=> $foo2;
1
if$foo1
is greater than$foo2
0
if$foo1
and$foo2
are equal
-1
if$foo1
is lower than$foo2
This does the same as the Python function I inplamented above.
Please note that I am not really a Perl coder, but have included this to show that other languages have a compareson feature.
Creating a function is all very well and works fine, however is there some (similar to what Perl uses) inbuilt function/operator that would compare these two values for me (rather than needing to build it myself)?