Change language

Python | cmp () function

|

The cmp () method in Python compares two integers and returns -1, 0, 1 as compared.

  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 program for demonstration
# using the cmp () method

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

Exit:

 -1 0 1 

Practical use: A program to check even or odd numbers using the cmp function.

Approach: compare 0 and n% 2, if it returns 0 then it is even, otherwise it is odd.

Below is the implementation of the above program in Python:

# Python program to check if a number is
# odd or even use of 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 

Python | cmp () function cmp: Questions

Python | cmp () function Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method