- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - cmp() Method
The cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.
Below example illustrates different scenario showing the use of cmp() method.
Example
def cmp(x, y): return (x > y) - (x < y) #x>y x = 5 y = 3 print("The cmp value for x>y is : ",cmp(x, y),"\n") #x<y x = 7 y = 9 print("The cmp value for x<y is : ",cmp(x, y),"\n") #x=y x = 13 y = 13 print("The cmp value for x=y is : ",cmp(x, y)) #odd and even k = 16 if cmp(0, k % 2): print("\n","The given number",k,"is odd number ") else: print("\n","The given number",k,"is even number") k= 31 if cmp(0, k % 2): print("\n","The given number",k,"is odd number") else: print("\n","The given number",k,"is even number")
Output
Running the above code gives us the following result −
The cmp value for x>y is : 1 The cmp value for x<y is : -1 The cmp value for x=y is : 0 The given number 16 is even number The given number 31 is odd number
- Related Articles
- Dictionary Methods in Python (cmp(), len(), items()…)
- What does the cmp() function do in Python Object Oriented Programming?
- Instruction type CMP R in 8085 Microprocessor
- Python - getattr() method
- Python - iter() method
- Class method vs static method in Python
- eval method in Python?
- dir() Method in Python
- Python – PyTorch clamp() method
- numpy.tri Method in Python
- numpy.tril Method in Python
- numpy.triu Method in Python
- numpy.vander Method in Python
- numpy.matrix Method in Python
- Explain Python class method chaining

Advertisements