Python | cmp() function

cmp() method in Python compares two integers and returns -1, 0, 1 according to comparison.

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
filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate the 
# use of cmp() method
  
# when a<b
a = 1 
b = 2 
print(cmp(a, b))  
  
# when a = b 
a = 2
b = 2 
print(cmp(a, b))  
  
# when a>b 
a = 3
b = 2 
print(cmp(a, b))

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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" 

chevron_right


Output:

even
odd


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : PK 1



Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.