Modulo Operator
Part of the Fundamentals section of Coddy's Python journey — lesson 11 of 77.
The modulo operator % tells you what's left over after dividing one number by another.
result = dividend % divisor- dividend: The number being divided.
- divisor: The number that divides the dividend.
- result: The remainder of the division.
For example
result = 10 % 3Here, 10 is divided by 3. 3 goes into 10 three times, with a remainder of 1. So, result will be 1.
Usually modulo is used for checking if a number is even or odd:
- If a number is even, dividing it by 2 will leave a remainder of 0.
- If a number is odd, dividing it by 2 will leave a remainder of 1.
To check this in code, we use the == operator, which checks if two values are equal to each other. For example, result == 0 asks "is result equal to 0?"
Special Case: When the dividend is smaller than the divisor, the result is simply the dividend itself.
For example:5 % 8 = 5
Why? Since 8 cannot fit into 5 even once, the entire 5 remains as the remainder.
Challenge
BeginnerWrite a code that initializes three variables, a, b and c with the values 9, 2, and 11 (respectively).
After that, initialize the following variables:
dthat will hold the result ofamodulo2ethat will hold the result ofbmodulo3fthat will hold the result ofcmodulo10
Check out the result and see how different dividends and divisors affect the result.
Cheat sheet
The modulo operator % returns the remainder of a division:
result = dividend % divisorExample:
result = 10 % 3 # result is 1Common use: checking if a number is even or odd
- Even number:
number % 2 == 0 - Odd number:
number % 2 == 1
Try it yourself
# Type your code below
# Don't change the line below
print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")
print(f"d = {d}")
print(f"e = {e}")
print(f"f = {f}")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2