Before you start this course, you must login to Replit
If you have forgotten your Replit account user name or password, ask your Coder Coach.
If you have forgotten your Replit account user name or password, ask your Coder Coach.
Examine and study each example carefully. Predict about what each example will do when it runs. Your prediction should be included as comments to the code (#).
Modulo (usually just called mod) performs integer division and returns the remainder only.
It uses the % operator.
For example:
3 % 1 = 3 remainder 0, so the value returned would be 0.
5 % 2 = 2 remainder 1, so the value returned would be 1.
14 % 4 = 3 remainder 2, so the value returned would be 2.
Modulo is really useful for working out whether a number is divisible by another one – if the remainder returned is 0 then the number is exactly divisible.
So to calculate if a number isodd or even you would mod it by 2, if the remainder is 0 then the number is even. ex:
remainder = num % 2
if remainder == 0:
print("Even number")
else:
print("Odd number")
Modulo can be used in conditions – better students may do this, but I make them do it the ‘long way round’ and assign the result to a variable until I’m happy that they have a solid understanding of the skill.
For example, the code above could also be written like this:
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
This removes the need for the vairable and makes the code shorter, but more syntactically dense and harder do undersatnd for new coders.
At the ‘predict’ & ‘run’ stages students work entirely with example code. They should inspect it carefully and write a prediction about what it will do.
They then run the code and compare the result to their prediction.
Make sure to check your code for the following mistakes: