Modulo#
Modulo Operator %#
The modulo operator % is common in programming languanges, but not so much in our typical engineering problems. It turns out it can be very useful in iteration loops. It’s actually quite simple: the expression a % b returns the remainder of a/b. That’s it!
Take a look at the following examples that illustrate the operator:
print(6 % 5)
print(5 % 6)
print(1 % 10)
print(5 % 5)
print(0 % 5)
1
5
1
0
0
You can’t divide by zero, just as in normal division.
Below is an illustration for how the modulo is useful for doing things in a for loop that doesn’t need to be done on every iteration.
for i in range(100):
if i%25 == 0:
print(i)
0
25
50
75
\(\text{Task 2.1:}\)
Experiment with the two Python cells above and make sure you understand what the modulo operator is and how it works.
We won’t do anything else with % now, but will apply this in the last task of the assignment.
By Robert Lanzafame, Delft University of Technology. CC BY 4.0, more info on the Credits page of Workbook.