← Python lessons

Python Operators: Floor Division //, Modulo % and Powers **

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Python's floor division // always rounds down, % gives a remainder with the sign of the divisor, and ** raises to a power. Negative numbers change how they behave.

Read Data Types and Operations first.

Floor division rounds down, not toward zero

"Down" means toward negative infinity. For negative results, that is away from zero.

print(7 // 2)
print(-7 // 2)
print(int(-7 / 2))

This prints 3, -4, then -3. int() cuts toward zero, so it differs from // for negatives.

Modulo with negative numbers

The result of % takes the sign of the number on the right. The two operators always fit together: (a // b) * b + a % b == a.

print(-7 % 2)
print(7 % -2)
print((-7 // 2) * 2 + -7 % 2)

This prints 1, -1, then -7. So n % 2 == 1 still finds odd numbers when n is negative.

Get both at once with divmod()

divmod(a, b) returns the floor division result and the remainder together.

minutes = 135
hours, left = divmod(minutes, 60)
print(hours, left)
print(divmod(-17, 5))

This prints 2 15, then (-4, 3). Use it when you need both parts, such as hours and minutes.

Raise to a power with **

a ** b multiplies a by itself b times. It runs before - on its left, so add brackets for a negative base.

print(2 ** 3)
print(-2 ** 2)
print((-2) ** 2)
print(9 ** 0.5)

This prints 8, -4, 4, then 3.0. A power of 0.5 is a square root, and gives a float.

Floats and dividing by zero

// and % work on floats too, and then give a float. Dividing by zero raises an error.

print(7.5 // 2)
print(7.5 % 2)
try:
    print(10 // 0)
except ZeroDivisionError:
    print("Cannot divide by zero")

This prints 3.0, 1.5, then Cannot divide by zero. Check the divisor first when it comes from user input.

See also: Modulo and divisibility.

Your turn

seconds holds a time that is before the start, so it is negative. Use divmod() to split it into minutes and seconds, and print both. Then print seconds / 60 cut toward zero with int().

seconds = -150
# add three lines: divmod into minutes and rest, print them, then print int(seconds / 60)

Expected output

-3 30
-2