How to do floor division in Python

Learn how to perform floor division in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

How to do floor division in Python
Published on: 
Fri
Feb 20, 2026
Updated on: 
Mon
Apr 6, 2026
The Replit Team

Floor division in Python, performed with the // operator, is a key operation for tasks that need integer results. It rounds down to the nearest whole number, unlike standard division.

Here, you'll explore techniques and practical tips for its use. We'll also cover real-world applications and provide debugging advice to help you master this essential Python feature.

Basic floor division with the // operator

a = 17
b = 5
result = a // b
print(f"{a} // {b} = {result}")--OUTPUT--17 // 5 = 3

In this example, the expression 17 // 5 evaluates to 3. While standard division (/) would yield 3.4, the floor division operator specifically truncates the decimal and returns the largest integer less than or equal to the result, contrasting with other division operations in Python.

This is useful when you're not interested in the remainder, only in how many times a number fits completely into another. It’s a clean way to get a whole number from a division operation without needing to call another function to round the result down.

Alternative floor division methods

While the // operator is the most direct way to perform floor division, Python also offers several other functions that can achieve a similar result.

Using the math.floor() function

import math
a = 17
b = 5
result = math.floor(a / b)
print(f"math.floor({a} / {b}) = {result}")--OUTPUT--math.floor(17 / 5) = 3

The math.floor() function provides another route to the same result. It works by first performing standard division with the / operator, which creates a float. The function then takes this float and rounds it down to the nearest whole number, similar to other floor operations in Python.

  • This method explicitly separates the division and rounding steps.
  • It's slightly more verbose than using the // operator.
  • Remember to import the math module to access the function.

Using the int() function for positive numbers

a = 17
b = 5
result = int(a / b)
print(f"int({a} / {b}) = {result}")
# Note: Behaves differently with negative numbers--OUTPUT--int(17 / 5) = 3

For positive numbers, you can also use the int() function in Python to achieve floor division. It works by truncating the result of a standard division, which means it simply removes the decimal part. This makes it a quick way to convert a float to an integer.

  • This approach is straightforward for positive outcomes.
  • However, its behavior differs with negative numbers, where it truncates toward zero instead of rounding down like the // operator.

Using the divmod() function

a = 17
b = 5
quotient, remainder = divmod(a, b)
print(f"divmod({a}, {b}) = ({quotient}, {remainder})")
print(f"Floor division result: {quotient}")--OUTPUT--divmod(17, 5) = (3, 2)
Floor division result: 3

The divmod() function is a handy built-in that combines two operations into one call. It's efficient because it calculates both the floor division result and the remainder at the same time, returning them as a single tuple.

  • The first value in the returned tuple is the quotient from floor division.
  • The second value is the remainder.

You can unpack this tuple directly into two variables, giving you immediate access to the floor division result without needing a second operation.

Advanced floor division techniques

With the fundamentals covered, you can apply the // operator to more nuanced scenarios, like handling negative numbers or building safer, more complex operations.

Handling negative numbers with //

positive = 17 // 5
negative = -17 // 5
print(f"17 // 5 = {positive}")
print(f"-17 // 5 = {negative}") # Rounds down, not toward zero--OUTPUT--17 // 5 = 3
-17 // 5 = -4

When you use the // operator with negative numbers, its behavior is consistent but can be surprising. The expression -17 // 5 results in -4 because floor division always rounds down toward negative infinity, not toward zero.

  • The result of standard division is -3.4, and the next lowest integer is -4.

This is a key difference from functions like int(), which would truncate the decimal and return -3. This predictable rounding makes // a reliable tool for mathematical operations where you need consistent floor behavior for both positive and negative values.

Floor division in list comprehensions

numbers = [17, 25, 33, 41, 50]
divided = [num // 5 for num in numbers]
print(f"Original numbers: {numbers}")
print(f"After floor division by 5: {divided}")--OUTPUT--Original numbers: [17, 25, 33, 41, 50]
After floor division by 5: [3, 5, 6, 8, 10]

List comprehensions provide a concise way to apply an operation to every item in a list. Here, the // operator is used to divide each number by 5, generating a new list containing the floor division results. This approach is much cleaner than writing a traditional for loop to accomplish the same task.

  • It’s a powerful method for transforming data collections quickly.
  • The entire operation is expressed in a single, readable line of code.

Creating a safe // operation with error handling

def smart_floor_div(a, b, default=None):
try:
return a // b
except ZeroDivisionError:
return default

print(smart_floor_div(17, 5))
print(smart_floor_div(17, 0, "Cannot divide by zero"))--OUTPUT--3
Cannot divide by zero

Division by zero will crash a program, but you can prevent this by wrapping the operation in a function. The smart_floor_div function uses try and except in Python to safely perform floor division. It attempts the // operation, and if a ZeroDivisionError occurs, it returns a default value instead of halting execution.

  • This makes your code more robust by anticipating and managing potential errors.
  • You can provide a custom fallback value or message, making debugging more straightforward.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques to building complete applications with Agent 4, which takes an idea to a working product directly from a description.

Instead of piecing together operators like //, you can describe the app you want to build and let Agent handle everything from the code to deployment. For example, you could create:

  • A pagination calculator that determines the total number of pages for a blog or e-commerce store.
  • A unit converter that transforms a total number of seconds into a more readable format of hours, minutes, and seconds.
  • A data binning tool that groups numerical data—like customer ages or product prices—into specific ranges for analysis.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While floor division is useful, a few common challenges can arise, including unexpected results with negative numbers, TypeErrors, and ZeroDivisionErrors.

Beware of negative numbers with the // operator

A frequent tripwire with the // operator is its behavior with negative numbers. It’s easy to assume it rounds toward zero, but it actually rounds down toward negative infinity. This subtle difference can lead to unexpected outcomes, as shown below.

# Assuming floor division always rounds toward zero
a = -17
b = 5
result = a // b
print(f"Expected: -3")
print(f"Got: {result}")

This common pitfall occurs because the // operator doesn't simply truncate the decimal with negative numbers. It rounds down, resulting in -4 instead of -3. The code below shows how to achieve truncation toward zero.

# Floor division rounds down, not toward zero
a = -17
b = 5
result = a // b
print(f"-17 // 5 = {result}") # Results in -4
# To round toward zero (truncate):
truncated = int(a / b)
print(f"int(-17 / 5) = {truncated}") # Results in -3

The // operator always rounds down toward negative infinity, so -17 // 5 evaluates to -4. If you need to truncate toward zero, first perform standard division and then convert the result to an integer with int(). This int(-17 / 5) approach yields -3. This distinction is critical in algorithms where consistent rounding toward zero is expected, especially when dealing with both positive and negative numbers.

Fixing TypeError when using // with strings

Another common issue is a TypeError, which occurs when you use the // operator on incompatible data types. You can't perform floor division on a string and an integer, even if the string contains digits. The code below shows this error.

user_input = "42"
divisor = 5
result = user_input // divisor
print(f"{user_input} // {divisor} = {result}")

This operation fails because user_input is a string, not a number. Python's // operator requires numerical types, so mixing a string and an integer triggers a TypeError. The corrected code below shows how to handle this.

user_input = "42"
divisor = 5
result = int(user_input) // divisor
print(f"{user_input} // {divisor} = {result}")

The fix is to explicitly convert the string to a number before division. By wrapping user_input in the int() function, you transform the string "42" into the integer 42, which allows the // operator to work as expected. This type of error is common when dealing with user input or data read from files, so it's a good practice to always validate and convert data types before performing mathematical operations.

Handling ZeroDivisionError in floor division

Handling ZeroDivisionError in floor division

Dividing by zero is mathematically undefined, and Python enforces this rule with a ZeroDivisionError. When your code attempts an operation like 100 // 0, the program immediately stops. It's a fatal error that you must handle to build robust applications. The code below shows how a function like calculate_ratio triggers this error, causing the program to crash.

def calculate_ratio(items, groups):
items_per_group = items // groups
return items_per_group

result = calculate_ratio(100, 0)
print(f"Items per group: {result}")

The calculate_ratio function fails because it's called with 0 for the groups parameter. This attempts the operation 100 // 0, which is mathematically invalid and triggers a ZeroDivisionError. The code below shows how to prevent this crash.

def calculate_ratio(items, groups):
if groups == 0:
return "Cannot divide by zero"
items_per_group = items // groups
return items_per_group

result = calculate_ratio(100, 0)
print(f"Items per group: {result}")

The fix is a simple conditional check. The if groups == 0: statement intercepts the zero before the division occurs, preventing the program from crashing. Instead, it returns a safe, informative message. This "guard clause" is a crucial pattern to use whenever a divisor's value isn't guaranteed—especially when working with user input or calculations where the denominator could dynamically become zero.

Real-world applications

With a solid grasp of how to avoid errors, you can apply the // operator to solve practical problems like pagination and time conversion.

Converting seconds to time units with //

By combining the // operator with the modulo operator in Python (%), you can easily break down a large number of seconds into a more human-readable structure of hours, minutes, and seconds.

total_seconds = 3750
hours = total_seconds // 3600
remaining = total_seconds % 3600
minutes = remaining // 60
seconds = remaining % 60
print(f"{total_seconds} seconds = {hours}h {minutes}m {seconds}s")

This snippet neatly converts a total number of seconds into a familiar hours, minutes, and seconds format. The logic hinges on a clever combination of floor division (//) and the modulo operator (%).

  • First, total_seconds // 3600 calculates the number of full hours contained within the total.
  • The modulo operator in total_seconds % 3600 then finds the leftover seconds.
  • This same pattern is repeated on the remaining seconds to find the minutes and final seconds.

This approach is a classic and efficient way to handle unit conversions in programming.

Calculating pagination with // operator

The // operator is also perfect for building pagination logic, helping you calculate how many pages are needed to display a large collection of items.

total_items = 87
items_per_page = 10
# Calculate total pages (using ceiling division)
total_pages = (total_items + items_per_page - 1) // items_per_page
current_page = 3
start_index = (current_page - 1) * items_per_page
end_index = min(start_index + items_per_page, total_items)
print(f"Total pages: {total_pages}")
print(f"Page {current_page} shows items {start_index+1}-{end_index} of {total_items}")

This code implements pagination logic by first calculating the total pages needed. The expression (total_items + items_per_page - 1) // items_per_page is a clever trick that uses floor division to simulate ceiling division, ensuring any remainder gets a full page.

  • The start_index is calculated to find the first item for the current page.
  • The end_index uses the min() function to safely cap the item range, which prevents index errors on the final page where there might be fewer than items_per_page.

Get started with Replit

Now, turn your knowledge of floor division into a real application. Describe what you want to build to Replit Agent, like "create a tool to distribute tasks evenly among a team" or "calculate grid rows for a gallery."

It writes the code, tests for errors, and deploys your app from your description, handling the entire development process for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.