
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements