logo

Python Number Cmp() Method


Show

Description

The cmp() method in Python number is known to return the sign of the difference between two numbers i.e. -1 if x < y, 0 if x == y, or 1 if x > y. The cmp() method in Python number refers to an in-built function that is used for the comparison of two or more objects and it returns a value as per the given values. The cmp() method in Python number returns negative, zero, or positive values depending on the input instead of true or false.

Syntax

Following is the syntax for cmp() method:

cmp( x, y )

Parameters

  • x - This is a numeric expression.
  • y - This is also a numeric expression.

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 cmp() method.

#!/usr/bin/python

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 the above program, it produces the following result:

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

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.