Skip to content

Python Floor Division: Complete Guide to the // Operator

Kanaries Team
Name
Kanaries Team

Updated on

Floor division is a fundamental arithmetic operation in Python that divides two numbers and rounds the result down to the nearest integer. Unlike regular division which returns a floating-point number, floor division using the // operator always returns the largest integer less than or equal to the result. This article will guide you through everything you need to know about Python floor division.

Python provides two division operators: the regular division operator / and the floor division operator //. Understanding when to use each is essential for writing efficient and bug-free Python code.

Want to quickly create Data Visualization from Python Pandas Dataframe with No code?

PyGWalker is a Python library for Exploratory Data Analysis with Visualization. PyGWalker (opens in a new tab) can simplify your Jupyter Notebook data analysis and data visualization workflow, by turning your pandas dataframe (and polars dataframe) into a tableau-alternative User Interface for visual exploration.

PyGWalker for Data visualization (opens in a new tab)

What is Floor Division in Python?

Floor division is the division operation that rounds the result down to the nearest whole number. In Python, this is performed using the // operator. The term "floor" comes from the mathematical floor function, which always rounds toward negative infinity.

Here's a simple example:

# Regular division
print(7 / 2)   # Output: 3.5
 
# Floor division
print(7 // 2)  # Output: 3

As you can see, regular division returns 3.5, while floor division returns 3 - the largest integer that is less than or equal to 3.5.

Floor Division Syntax

The syntax for floor division in Python is straightforward:

result = dividend // divisor

Where:

  • dividend is the number being divided
  • divisor is the number you're dividing by
  • result is the floor of the division

Floor Division with Different Data Types

Integers

When both operands are integers, floor division returns an integer:

print(10 // 3)   # Output: 3
print(15 // 4)   # Output: 3
print(20 // 5)   # Output: 4

Floating-Point Numbers

When at least one operand is a float, floor division returns a float (but still rounded down):

print(10.0 // 3)   # Output: 3.0
print(10 // 3.0)   # Output: 3.0
print(10.5 // 3)   # Output: 3.0

Negative Numbers

Floor division with negative numbers can be tricky. Remember, floor division always rounds toward negative infinity, not toward zero:

print(7 // 2)    # Output: 3
print(-7 // 2)   # Output: -4  (not -3!)
print(7 // -2)   # Output: -4
print(-7 // -2)  # Output: 3

This behavior is important to understand because -7 / 2 = -3.5, and the floor of -3.5 is -4, not -3.

Floor Division vs Regular Division

OperationOperatorResult TypeExampleOutput
Regular Division/Always float7 / 23.5
Floor Division//int or float7 // 23
# Comparison
a = 17
b = 5
 
print(f"Regular division: {a} / {b} = {a / b}")     # 3.4
print(f"Floor division: {a} // {b} = {a // b}")     # 3

Practical Use Cases for Floor Division

1. Calculating Pages or Groups

When you need to determine how many complete groups fit within a total:

total_items = 23
items_per_page = 5
 
complete_pages = total_items // items_per_page
print(f"Complete pages: {complete_pages}")  # Output: 4

2. Converting Units

Floor division is useful for unit conversions:

total_seconds = 3725
 
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
 
print(f"{hours}h {minutes}m {seconds}s")  # Output: 1h 2m 5s

3. Array Indexing and Positioning

When working with grids or 2D arrays:

# Convert 1D index to 2D coordinates
index = 17
columns = 5
 
row = index // columns
col = index % columns
 
print(f"Index {index} -> Row: {row}, Column: {col}")  # Row: 3, Column: 2

4. Finding Middle Index

Useful in binary search and similar algorithms:

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
 
    while left <= right:
        mid = (left + right) // 2  # Floor division for middle index
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
 
    return -1

The divmod() Function

Python provides a built-in function divmod() that returns both the quotient (floor division) and remainder in a single operation:

quotient, remainder = divmod(17, 5)
print(f"17 // 5 = {quotient}")    # Output: 3
print(f"17 % 5 = {remainder}")     # Output: 2

This is more efficient than calling // and % separately when you need both values.

Floor Division with the math Module

You can also achieve floor division using the math.floor() function combined with regular division:

import math
 
result1 = 7 // 2
result2 = math.floor(7 / 2)
 
print(result1)  # Output: 3
print(result2)  # Output: 3

Both methods produce the same result, but // is more concise and generally preferred.

Common Mistakes and How to Avoid Them

Mistake 1: Confusing Floor Division with Truncation

# Floor division rounds toward negative infinity
print(-7 // 2)  # Output: -4
 
# Truncation (int conversion) rounds toward zero
print(int(-7 / 2))  # Output: -3

Mistake 2: Forgetting About Float Results

# If one operand is float, result is float
print(type(10 // 3))    # <class 'int'>
print(type(10.0 // 3))  # <class 'float'>

Mistake 3: Division by Zero

# This will raise ZeroDivisionError
try:
    result = 10 // 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Performance Considerations

Floor division is generally faster than regular division followed by int() or math.floor():

import timeit
 
# Floor division operator
time1 = timeit.timeit('7 // 2', number=1000000)
 
# Regular division + int()
time2 = timeit.timeit('int(7 / 2)', number=1000000)
 
print(f"// operator: {time1:.4f}s")
print(f"int(/) method: {time2:.4f}s")

FAQ

What is the difference between / and // in Python?

The / operator performs true division and always returns a float, while // performs floor division and returns the largest integer less than or equal to the result. For example, 7 / 2 returns 3.5, but 7 // 2 returns 3.

How does floor division work with negative numbers?

Floor division always rounds toward negative infinity. So -7 // 2 equals -4, not -3, because -4 is the largest integer less than or equal to -3.5.

When should I use floor division instead of regular division?

Use floor division when you need an integer result and want to avoid floating-point precision issues, such as calculating array indices, counting complete groups, or implementing algorithms that require integer arithmetic.

Conclusion

Python floor division with the // operator is a powerful tool for performing integer division that rounds down to the nearest whole number. Understanding its behavior, especially with negative numbers and floating-point operands, is crucial for writing correct Python code. Whether you're implementing algorithms, converting units, or working with array indices, floor division is an essential operation in your Python toolkit.