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.
Example
# Example 1
print(cmp(3, 4))
# Example 2
print(cmp(5, 5))
# Example 3
print(cmp(7, 6))
Output
-1
0
1
Explanation
- In the first example, 3 is smaller than 4, so the function returns -1.
- In the second example, 5 is equal to 5, so it returns 0.
- In the third example, 7 is greater than 6, so it returns 1.
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 of cmp() function
cmp(x, y)
Parameters
- x: The first value to compare.
- y: The second value to compare.
Return Type
- 0 if x == y (both are equal).
- 1 if x > y (first value is greater).
- -1 if x < y (first value is smaller).
Example of cmp() function
Checking if a Number is Even or Odd
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 program to check if a number is
# odd or even using cmp function
# check 12
n = 12
if cmp(0, n % 2):
print"odd"
else:
print"even"
# check 13
n = 13
if cmp(0, n % 2):
print"odd"
else:
print"even"
Output
even
odd
Explanation
- The cmp() function was used to compare 0 and n % 2 to check if the number is even or odd.
- In Python 3, you can directly use comparison operators like == to achieve the same result without using cmp().