
Syntax: Remainders
Finding the remainder from dividing one integer by another with the Python remainder operator.
Division Remainders in Python
When a developer needs the remainder value which is left after performing integer division, the operator to use is the modulo operator. The name for the operator comes from the branch of mathematics named modular arithmetic. It is also sometimes called the remainder operator.
The important thing to remember with the modulo operator is that is returns the remainder that is left after division between two numeric values. The modulo operator can be used with numerous number types in Python. This exercise will focus on its use with integer values.
Check out the example output below:
14 % 4
2
Note that the number returned from 14 % 4 is two because 4 goes into 14 three times with 2 left over. The modulo operator will always return the remainder of division.
Typical syntax usage for the modulo operator are as follows:
-
When finding the remainder of dividing two integer values:
remainder = 25 % 5 -
When finding the remainder of a variable with an integer value and another integer:
val = 53 remainder = val % 3 -
When finding the remainder of two variables with integer values:
val1 = 31 val2 = 7 remainder = val1 % val2
Practice: Calculating Integer Remainders
Based on the above information, please complete the following steps:
- Define a variable named
pizza_slicesand assign it the value12. - Define a variable named
siblingsand assign it the value5. - Define a variable named
leftover_slicesand, using the modulus operator, assign it the number of remaining slices after distributing the available slices evenly between siblings. - Print the value contained in the
leftover_slicesvariable.
HINT*: Click here for a hint
You should see the number of leftover slices:
> 2
SOLUTION*: Click here for an example solution
pizza_slices = 12
siblings = 5
leftover_slices = pizza_slices % siblings
print(leftover_slices)
Another thing to be aware of with the modulo operator is that it is often used for finding out if a integer value is even or odd.
Any number which is divided by 2 and has no remainder is an even number. Note the examples below:
24 % 2
0
7824 % 2
0
19854 % 2
0
Based on this information, it is also important to conclude that any number divided by 2 which does not have zero for a remainder is an odd value.
You will be learning more about how to use the modulo operator to programmatically find even and odd values in later exercises.
For now, you are ready to move on to the next exercise!