cmp() method in Python 2.x compares two integers and returns -1, 0, 1 according to comparison. cmp() does not work in python 3.x. You might want to see list comparison in Python.
Note
The cmp function was a built-in function in Python 2 for comparing the values of two objects.
It has been removed in Python 3 and replaced with the == and is operators, which provide more robust and flexible comparison functionality.
Syntax:
cmp(a, b)
Parameters:
a and b are the two numbers in which the comparison is being done.
Returns:
-1 if a<b
0 if a=b
1 if a>b
Python
a = 1
b = 2
print(cmp(a, b))
a = 2
b = 2
print(cmp(a, b))
a = 3
b = 2
print(cmp(a, b))
|
Output:
-1
0
1
Practical Application: Program to check if a number is even or odd using cmp function. Approach: Compare 0 and n%2, if it returns 0, then it is even, else its odd. Below is the Python implementation of the above program:
Python
n = 12
if cmp(0, n % 2):
print"odd"
else:
print"even"
n = 13
if cmp(0, n % 2):
print"odd"
else:
print"even"
|
Output:
even
odd