Python - cmp() Method


The cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.

Below example illustrates different scenario showing the use of cmp() method.

Example

 Live Demo

def cmp(x, y):
   return (x > y) - (x < y)
#x>y
x = 5
y = 3
print("The cmp value for x>y is : ",cmp(x, y),"\n")
#x<y
x = 7
y = 9
print("The cmp value for x<y is : ",cmp(x, y),"\n")
#x=y
x = 13
y = 13
print("The cmp value for x=y is : ",cmp(x, y))
#odd and even
k = 16
if cmp(0, k % 2):
   print("\n","The given number",k,"is odd number ")
else:
   print("\n","The given number",k,"is even number")
k= 31
if cmp(0, k % 2):
   print("\n","The given number",k,"is odd number")
else:
   print("\n","The given number",k,"is even number")

Output

Running the above code gives us the following result −

The cmp value for x>y is : 1

The cmp value for x<y is : -1

The cmp value for x=y is : 0

The given number 16 is even number

The given number 31 is odd number

Updated on: 03-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements