← Back

Home › Output practice › // and % with negative numbers

Predict the output: // and % with negative numbers

🔮 Predict the outputTopic: numbersDifficulty: mediumNo login needed

The snippet

This is the question where Python differs from C, Java and most calculators. // does not chop the decimal off — it floors, meaning it moves to the smaller integer, i.e. left on the number line.

print(7 // 2, 7 % 2)
print(-7 // 2, -7 % 2)

Your prediction

Type exactly what this program prints — one line per print() call:

The output

3 1
-4 1

Verified against CPython 3.11 in this repo's build

Line-by-line explanation

  1. 7 // 2
    7/2 = 3.5; floor(3.5) = 3 → 3.
  2. 7 % 2
    a % b is defined as a - b * (a // b) → 7 − 2×3 = 1.
  3. -7 // 2
    -3.5 floored moves *away* from zero → -4. This single line is where most predictions break.
  4. -7 % 2
    −7 − 2×(−4) = −7 + 8 = 1. The remainder keeps the sign of the divisor, not of the dividend.
  5. check yourself
    b * (a // b) + a % b == a always holds: 2×(−4)+1 = −7 ✓. Use it as a two-second audit in an exam.

The rule you can reuse

// floors, so with a negative operand it rounds away from zero; % takes the sign of the right-hand number. math.trunc(a / b) is the "chop toward zero" behaviour you may have learned elsewhere.

Why most predictions break here

Answering -3 and -1 (truncating division, as in C/Java). Python's pairing is deliberately chosen so that modulo stays usable for calendar and clock arithmetic.

Quick fire

Same rule, two more shapes. Predict first, then open.

Predict this too
print(9 // -2, 9 % -2)
print(divmod(-9, 4))

Output
-5 -1
(-3, 3)

Now the divisor is negative, so the remainder follows it: -5 -1; divmod returns the same pair as a tuple → (-3, 3).

Predict this too
print(7 / 2, 7 // 2, type(7 / 2).__name__)

Output
3.5 3 float

/ always makes a float, even when it divides exactly → 3.5 3 float.

Share your result

Challenge a friend — the link contains the question, never the answer:

Copied ✓

Keep practising this rule

More output questions → All interactive problems

Questions this page answers

How do I round toward zero instead?

int(a / b) or math.trunc(a / b) (−3 for -7/2), or -(-a // b) when you want to stay in integer arithmetic.

Where does this actually bite?

Any "Nth item" or "minutes since epoch" arithmetic with negative offsets, and every i % n rotation on a reversed index — a negative modulo there silently yields a positive slot.