True Division and Floor Division in Python
True Division and Floor Division in Python
Python is a powerful and beginner-friendly programming language. One common task in programming is division, and Python provides two types of division operations:
- True Division
- Floor Division.
Understanding the difference between these two is essential for writing correct and efficient code.
True Division in Python
True Division returns the exact quotient of the division, including the decimal part. It is performed using the `/` operator.
For example:
“`python
result = 7 / 2
print(result) # Output: 3.5
In this example, 7 divided by 2 results in 3.5, which includes the fractional part.
Floor Division in Python
Floor Division returns the largest integer less than or equal to the result of the division. It is performed using the // operator.
For example:
result = 7 // 2
print(result) # Output: 3
Here, the result of 7 divided by 2 is 3.5, but floor division truncates the decimal part and returns 3.
/ and // Operators in Python
The / operator performs True Division.
The // operator performs Floor Division.
These operators behave differently based on the type of values (integers or floats) and the version of Python being used.
Python 2 vs Python 3
The differences between Python 2 and Python 3 division are as follows:
Python 2 | Python 3 | |
---|---|---|
`/` with integers | Performs Floor Division | Performs True Division |
`/` with floats | Performs True Division | Performs True Division |
`//` operator | Introduced in Python 2.2, explicitly for Floor Division | Used for Floor Division |
Result of `7 / 2` | 3 | 3.5 |
Examples
Some of the examples are shown as follows:
# True Division
print(10 / 4) # Output: 2.5
# Floor Division
print(10 // 3) # Output: 3
# Mixed types
print(10.0 / 4) # Output: 2.5
print(10.0 // 4) # Output: 2.0
# Negative numbers
print(-10 / 4) # Output: -2.5
print(-10 // 4) # Output: -3 (floor goes towards negative infinity)
Understanding the difference between / and // helps avoid unexpected results in your Python programs. It is recommended to always use the operator that best fits your intention: / for precise division results, and // when only whole numbers are needed.
Python Tutorials
Python Tutorial on this website can be found at: