Func Number Cmp
# Python cmp() Function
The `cmp()` function is a built-in utility used to compare two objects. While it is commonly used to compare numbers, it can also compare other types of objects.
> **Important Note on Python Versions:**
> The `cmp()` function is only available in **Python 2**. It was completely removed in **Python 3**. If you are using Python 3, you should use alternative comparison methods (such as relational operators or the `operator` module) as detailed in the (#python-3-alternatives) section below.
---
## Description
The `cmp(x, y)` function compares two values, $x$ and $y$, and returns an integer based on the comparison:
* Returns `-1` if $x < y$
* Returns `0` if $x == y$
* Returns `1` if $x > y$
---
## Syntax
```python
cmp(x, y)
```
### Parameters
* **`x`** -- A numeric expression or any comparable object.
* **`y`** -- A numeric expression or any comparable object.
### Return Value
* **`-1`** if $x$ is less than $y$.
* **`0`** if $x$ is equal to $y$.
* **`1`** if $x$ is greater than $y$.
---
## Code Examples
### Basic Usage (Python 2)
The following example demonstrates how `cmp()` works with different positive and negative integers:
```python
#!/usr/bin/python
# Comparing a smaller number to a larger number
print "cmp(80, 100) : ", cmp(80, 100)
# Comparing a larger number to a smaller number
print "cmp(180, 100) : ", cmp(180, 100)
# Comparing a negative number to a positive number
print "cmp(-80, 100) : ", cmp(-80, 100)
# Comparing a positive number to a negative number
print "cmp(80, -100) : ", cmp(80, -100)
```
**Output:**
```text
cmp(80, 100) : -1
cmp(180, 100) : 1
cmp(-80, 100) : -1
cmp(80, -100) : 1
```
---
## Python 3 Alternatives
If you are writing modern Python 3 code, calling `cmp()` will raise a `NameError: name 'cmp' is not defined`. You can achieve the exact same functionality using the following approaches:
### 1. Using Relational Operators (Recommended)
You can easily replicate the behavior of `cmp(x, y)` using boolean expressions:
```python
# Equivalent to cmp(x, y) in Python 3
def cmp(x, y):
return (x > y) - (x < y)
# Example usage:
print(cmp(80, 100)) # Output: -1
print(cmp(100, 100)) # Output: 0
print(cmp(180, 100)) # Output: 1
```
### 2. Using the `operator` Module
If you need to perform comparisons for sorting or functional programming, Python 3's `operator` module provides rich comparison operators:
```python
import operator
x = 80
y = 100
# Individual comparisons
print(operator.lt(x, y)) # True (Equivalent to x < y)
print(operator.eq(x, y)) # False (Equivalent to x == y)
print(operator.gt(x, y)) # False (Equivalent to x > y)
```
YouTip