Introduction:
In this lesson, we’ll be learning about two important arithmetic operators: floor division and modulo division. These might sound complicated, but don’t worry, they’re simpler than they seem, and we use these concepts in everyday life all the time!
Real-World Application Example:
Imagine you have a pile of sweets and you want to divide them equally among your friends. Floor division helps you figure out how many sweets each person will get, while modulo division tells you how many will be left over.
For example, if you have 10 sweets and 3 friends, each friend will get 3 sweets (that’s the result of floor division), and you’ll have 1 sweet left over (that’s the result of modulo division).
Here’s an example of how this works in Python:
# Floor division: prints 3 (each person gets 3 sweets) print(10 // 3) # Modulo division: prints 1 (1 sweet is left over) print(10 % 3)
Predict:
Let’s start by predicting what the following code will output. Think carefully about what happens when we use floor division (//
) and modulo division (%
):
print(17 // 4) print(17 % 4)
Take a moment to guess the result.
Hint: Floor division will give you how many times 4 goes into 17, and modulo division will give you the remainder.
Run:
Now, it’s time to run some code and see floor division and modulo division in action. Try the following code in the IDE and observe the results:
Explanation:
- The floor division (
//
) will tell you how many whole times 5 fits into 23. - The modulo (
%
) will tell you the remainder after dividing 23 by 5.
Investigate:
Now that you’ve seen how floor division and modulo work, let’s dig a little deeper into how they behave with different numbers.
Try running the following code and observe the results:
Instructions:
- Floor Division: Notice how
25 // 4
gives6
. This is because 4 fits into 25 exactly 6 times, and Python discards any decimal point or remainder when performing floor division. - Modulo Division: Now look at
25 % 4
. The result is1
. This tells you that when 25 is divided by 4, there is a remainder of 1.
Test Your Understanding:
- Try changing the numbers in the code. For example, what happens when you divide 29 by 6 using floor division and modulo?
Can you predict the result before running the code?
Hint: Think about how many times 6 fits into 29 and what will be left over!
Modify:
Let’s fix a small mistake in the code below. It’s supposed to calculate how many times 9 fits into 34 using floor division, and how many are left over using modulo division. Can you correct the error?
Hint: Replace the incorrect operators (/
and &
) with the appropriate ones for floor and modulo division.