Arithmetic, Floor & Power

Go beyond the basics of //, ** and % — including how they behave with negatives and floats.

You have met + - * / already. Here we look closely at the three operators that trip people up years into their career: floor division //, exponentiation **, and the remainder %.

Floor division rounds down, not toward zero

This is the classic surprise. // always rounds toward negative infinity, so -7 // 2 is -4, not -3. The remainder % follows along so that the identity (a // b) * b + (a % b) == a always holds.

print(7 // 2)     # 3
print(-7 // 2)    # -4  (rounds DOWN, not toward zero)
print(7 % 3)      # 1
print(-7 % 3)     # 2  (result takes the sign of the divisor)

Power does more than you think

** handles integers, floats, roots (fractional exponents) and even modular exponentiation via the three-argument pow(). And because Python integers never overflow, 2 ** 1000 is an exact answer, not a rounded one.

divmod: quotient and remainder together

When you need both at once — think converting seconds to minutes-and-seconds — reach for divmod(a, b), which returns the pair in a single call.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A scheduler uses -7 // 2 to calculate the correct floor-division result when handling negative offsets.
  • A cryptography module relies on the modulo of negative numbers behaving differently from C to keep values positive.
  • A compiler optimiser uses ** with large exponents and integer bases to generate test cases for overflow detection.

More examples

Floor division with negatives

Shows that // always floors toward negative infinity, which differs from C-style truncation for negative operands.

Example · python
print(7 // 2)    #  3  (floor toward -inf)
print(-7 // 2)   # -4  (not -3!)
print(7 // -2)   # -4
print(-7 // -2)  #  3

Modulo with negative numbers

Demonstrates that Python's modulo result always carries the sign of the divisor, and divmod() returns both at once.

Example · python
print( 7 % 3)    #  1
print(-7 % 3)    #  2  (result has sign of divisor)
print( 7 % -3)   # -2
divmod(-7, 3)    # (-3, 2)  — floor div + mod together

Integer exponentiation and modular power

Shows Python's arbitrary-precision integers with ** and the three-argument pow() for efficient modular exponentiation.

Example · python
print(2 ** 32)            # 4294967296 (no overflow)
print(pow(2, 100))        # exact big int
print(pow(2, 100, 13))    # modular exponentiation: fast!
print(2 ** 0.5)           # 1.4142... (float result)

Discussion

  • Be the first to comment on this lesson.