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.11 Modulo Modify

Instructions:


Adjust the starter code in main to complete the following instructions:

  • It gets user input into the ‘name variable’

  • It uses selection to print suitable messages depending on whether the name has an odd or even number of characters

  • Remove the need for the ‘name_length’ and ‘name_remainder’ variables by using len and modulus in the condition for the selection.

Modulo

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.

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

Predict & Run

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.

Help! My Code Does Not Work!

Make sure to check your code for the following things:

  • 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