Study Guides/Computer Science/Floor Division in Python
Study Guide ยท Computer Science

Floor Division in Python ( // Operator)

Floor Division in Python is performed using the // (double forward slash) operator. Unlike regular division (/), floor division always rounds down the result to the nearest whole number (integer), regardless of whether the numbers are positive or negative.

Question (Click to Flip)

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

Answer

/ is true division โ€” it always returns a float (e.g., 7/2 = 3.5). // is floor division โ€” it returns the largest integer โ‰ค the true result (e.g., 7//2 = 3). If both operands are integers, // returns an int; if either is a float, it returns a float.

Card 1 of 1 free previews

Key Facts

The modulo operator % in Python is closely related to floor division. The identity a = (a // b) * b + (a % b) always holds true, which is Python's equivalent of Euclid's Division Lemma.

How Floor Division Works

The // operator divides the left number by the right number and then floors the result โ€” meaning it rounds down to the nearest integer.

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

# Floor division
print(7 // 2)  # Output: 3  (rounds DOWN from 3.5)

print(10 // 3)  # Output: 3  (10/3 = 3.33... โ†’ rounds to 3)
print(15 // 4)  # Output: 3  (15/4 = 3.75 โ†’ rounds to 3)

Floor Division with Negative Numbers

This is where floor division behaves differently from simple truncation. For negative numbers, 'rounding down' means going further away from zero (toward more negative values).

print(-7 // 2)   # Output: -4  (NOT -3!)
# -7/2 = -3.5 โ†’ floor rounds DOWN to -4

print(7 // -2)   # Output: -4
# 7/-2 = -3.5 โ†’ floor rounds DOWN to -4

print(-7 // -2)  # Output: 3
# -7/-2 = +3.5 โ†’ floor rounds DOWN to 3

Questions and Answers

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

`/` is true division โ€” it always returns a `float` (e.g., 7/2 = 3.5). `//` is floor division โ€” it returns the largest integer โ‰ค the true result (e.g., 7//2 = 3). If both operands are integers, `//` returns an int; if either is a float, it returns a float.

More in Computer Science

Study Smarter with Shinyu.ai

Turn this guide into revision flashcards, a practice exam, or an AI-generated podcast โ€” free, no signup required.