In Python, floor division is the process of dividing two numbers and returning the quotient as an integer by rounding down the result to the nearest integer. The ‘//’ operator is used for floor division in Python.
For example, consider the following code:
print(10 // 3) # 3
As you can see, the line of code uses the ‘//’ operator to perform floor division and returns the quotient as an integer (3).
It’s also possible to use the math.floor() function to perform floor division.
import math print(math.floor(10 / 3)) # 3
It’s worth noting that in Python 2, the ‘/’ operator performs floor division if both operands are integers.
However, it’s generally recommended to use the ‘//’ operator or math.floor() function for floor division in Python 2 and Python 3 to avoid confusion and ensure that your code works correctly across different versions of Python.
In contrast to the true division operator ‘/’ that returns a float, floor division rounds down the division result to the nearest integer, it returns an integer.
print(10 / 3) # 3.333333
In summary, floor division in Python is the process of dividing two numbers and returning the quotient as an integer by rounding down the result to the nearest integer. The ‘//’ operator is used for floor division by default in Python 3.
In Python 2, the ‘/’ operator performs floor division if both operands are integers. It’s also possible to use the math.floor() function to perform floor division.
It’s always recommended to use the ‘//’ operator or math.floor() function in Python 2 and Python 3 to ensure that your code works correctly across different versions of Python.