Python math.cmp() Method



The Python math.cmp() method is used to compare two numbers. This method accepts two numeric values, say x and y, as arguments and returns the sign of the difference of two numbers : -1 if x < y, 0 if x == y, or 1 if x > y.

This method is only executable in Python 2.x versions and does not work in Python 3.x.

Syntax

Following is the syntax for the Python math.cmp() method −

math.cmp( x, y )

Parameters

  • x , y − These are the numeric values to be compared.

Return Value

This method returns -1 if x < y, returns 0 if x == y and 1 if x > y

Example

The following example shows the usage of the Python math.cmp() method. In here, we are passing two numbers as arguments to this method and the return values are displayed. However, this method only works in Python 2.

print "cmp(80, 100) : ", cmp(80, 100)
print "cmp(180, 100) : ", cmp(180, 100)
print "cmp(-80, 100) : ", cmp(-80, 100)
print "cmp(80, -100) : ", cmp(80, -100)

When we run above program, it produces following result −

cmp(80, 100) :  -1
cmp(180, 100) :  1
cmp(-80, 100) :  -1
cmp(80, -100) :  1

Example

But, to compare two numbers in Python 3, a user-defined function that works similar to this built-in cmp() method can be defined as given in the example below.

Here, we are defining a function "cmp", which takes two parameters x and y. When it is called in three cases ( x > y, x < y, x = y), this user-defined function returns the sign difference of the values x and y.

def cmp(x, y):
   return (x > y) - (x < y)
#x > y
x = 17
y = 11
print("The cmp value for x>y is : ",cmp(x, y),"\n")
#x<y
x = 5
y = 33
print("The cmp value for x<y is : ",cmp(x, y),"\n")
#x=y
x = 20
y = 20
print("The cmp value for x=y is : ",cmp(x, y))

The cmp value for x>y is :  1 

The cmp value for x<y is :  -1 

The cmp value for x=y is :  0
python_maths.htm
Advertisements