← Home

019. Floor Division

Integer quotient without remainder

019. Floor Division

RAM Manager — Pagination of Process List

Aryan’s RAM manager displays the top memory consumers in pages of 10 processes each. Given the total number of processes, he needs to know how many complete pages there are and how many processes appear on the last (partial) page.

Total processes: 47
Full pages:      4   (processes 1-40)
Last page:       7   (processes 41-47)

He writes paginate(total, page_size) returning (full_pages, remainder), but uses / instead of //. That means 47 / 10 returns 4.7 (a float) instead of 4 (an integer), and his page-number display shows "Page 4.7 of 4.7" — nonsense.

The lesson: Python’s / always returns a float. Use // (floor division) when you need a whole-number quotient — page numbers, array indices, and time conversions all require integers, not fractions.


💡 Fun fact: Floor division // rounds toward negative infinity, not toward zero — so -7 // 2 is -4, not -3. This is mathematically consistent with the modulo guarantee n == (n // k) * k + (n % k), but it surprises developers coming from C where integer division truncates toward zero.

⚠️ Watch out: Using / where // is needed returns a float, which will cause a TypeError if you later use the result as a list index or pass it to range(). The error message (“float object cannot be interpreted as an integer”) points to the wrong place — the real bug was using / instead of // earlier.

🤔 Think about it: 3600 // 3600 gives 1, and 3600 / 3600 gives 1.0. Both look the same when printed — so how would you catch this type mismatch before it causes a crash downstream?

Learning objectives

  • Use // for integer quotient (floor division)
  • Combine // and % to extract multi-unit values
  • Understand the difference between / and //

Key concepts

  • floor division
  • //
  • integer arithmetic

Try it

Concept detail

Floor division (//) divides and rounds DOWN to the nearest integer. 7 // 2 = 3 (not 3.5). -7 // 2 = -4 (rounds down, towards negative infinity). If both operands are int, result is int. If either is float, result is float. The pattern for extracting place values: quotient = n // base, remainder = n % base. Classic use cases: convert seconds to h/m/s, convert minutes to hours, pagination.

Solution

def seconds_to_hms(total_seconds):
    hours = total_seconds // 3600
    minutes = (total_seconds // 60) % 60
    seconds = total_seconds % 60
    return hours, minutes, seconds

Tests

def test_one_hour():
    h, m, s = seconds_to_hms(3600)
    assert h == 1 and m == 0 and s == 0

def test_mixed():
    h, m, s = seconds_to_hms(3661)
    assert h == 1 and m == 1 and s == 1

def test_hours_is_int():
    h, m, s = seconds_to_hms(3600)
    assert type(h) == int

def test_under_one_hour():
    h, m, s = seconds_to_hms(90)
    assert h == 0 and m == 1 and s == 30

def test_zero():
    h, m, s = seconds_to_hms(0)
    assert h == 0 and m == 0 and s == 0

Resources