replit

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.

CodeSports

5.12-Modulo-Make

Modulo


Modulo (usually just called mod) performs integer division and returns the remainder only.

It uses the % operator.

Slide Deck


The slides to accompany this topic [are here] (https://docs.google.com/presentation/d/1KN5LkKUI5LiVpOnr27HTCMtdODOqScXQ8LnROVvtOwI/edit?usp=sharing)

Teacher Notes


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.

Code Examples


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 is odd 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 variable and makes the code shorter, but more syntactically dense and harder do understand for new coders.

Make


In the make tasks, students use the skills learned in the earlier stages of PRIMM to create their own program based on a description of what it should do.

Make sure that the students add comments to explain what the code does.

Help! My Code Does Not Work!


When you encounter errors in your code, make sure to check:

  • use a single % as the operator
  • a number or number variable either side of the operator
  • assign the remainder to a variable (or better students may use it straight in a condition)

Hints