How To Use The % Operator: A Set of Python Modulo Examples

Basic Remainder Calculation

The % operator returns the remainder when dividing one number by another. Example: 10 % 3 equals 1 because 10 ÷ 3 leaves a remainder of 1.

Check for Even or Odd Numbers

Use % 2 to determine if a number is even (x % 2 == 0) or odd (x % 2 != 0). It's a common application of modulo in programming.

Looping Back to Start in Cycles

In cyclic patterns (like days of the week), % helps reset counts. Example: (day + n) % 7 keeps days within a week range (0–6).

Divisibility Tests

Use % to check if one number is divisible by another. Example: x % y == 0 returns True if x is fully divisible by y.

Digit Extraction

Use % with 10, 100, etc., to extract digits. Example: 123 % 10 isolates the last digit (3), while 123 % 100 gives the last two digits (23).

Wrapping Index in Lists

% is useful for looping through list indices. Example: index % len(list) ensures index stays within bounds, even if it's larger than the list size.