- Related Questions & Answers
- 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
- Explain Python class method chaining
- destroy() method in Tkinter - Python
- Python - geometry method in Tkinter
- after method in Python Tkinter
- What is zfill() method in Python?
- What is random.uniform method in Python?
- What is weekday() method in python?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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

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

Advertisements