Home » Python

Python - cmp() function with Example

Python - cmp() function with example: In this article, we are going to learn about cmp() function in python, which is an in-built function in python and used to compare two object.
Submitted by IncludeHelp, on January 21, 2018

Python - cmp() function

cmp() is an in-built function in Python, it is used to compare two objects and returns value according to the given values. It does not return 'true' or 'false' instead of 'true' / 'false', it returns negative, zero or positive value based on the given input.

Syntax: cmp(obj1, obj2)

Here, cmp() will return negative (-1) if obj1<obj2, zero (0) if obj1=obj2, positive (1) if obj1>obj2.

Example:

    Input:
    num1 = 10, num2 = 20
    Output:
    cmp(10, 20) will return -1
    because 10<20

    Input:
    num1 = 10, num2 = 10
    Output:
    cmp(10, 10) will return 0
    because 10=10


    Input:
    num1 = 20, num2 = 10
    Output:
    cmp(20, 10) will return 
    because 20>10

# Python code to demonstrate example of cmp()

In this example, we are comparing two integer values and two strings.

# Python code to demonstrate example of cmp()

# comparing integer values
print "Result of cmp(int,int)..."
print "cmp(10,20): ", cmp(10,20)
print "cmp(10,10): ", cmp(10,10)
print "cmp(20,10): ", cmp(20,10)

# comparing string values
print "Result of cmp(string,string)..."
print "cmp('ABC','PQR'): ", cmp('ABC','PQR')
print "cmp('ABC','ABC'): ", cmp('ABC','ABC')
print "cmp('PQR','ABC'): ", cmp('PQR','ABC')

Output

Result of cmp(int,int)...
cmp(10,20):  -1
cmp(10,10):  0
cmp(20,10):  1
Result of cmp(string,string)...
cmp('ABC','PQR'):  -1
cmp('ABC','ABC'):  0
cmp('PQR','ABC'):  1





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.