The / operator will always give you a float as a result.
320 / 20
403.0 / 24.0
Sometimes, instead of getting the full floating-point expansion, you might want the quotient and remainder separately.
The // is the floor division operator - it gives you the quotient and ignores and fractional/remainder part.
320 // 20
403 // 24
The % operator is the modulo operator - another word for remainder - it will ignore the quotient and just give you the remainder.
403 // 24
403 % 24
Try each of the following in your interactive shell. What pattern do you notice?
0 // 2
1 // 2
3 // 2
4 // 2
5 // 2
6 // 2
20 // 5
21 // 5
22 // 5
23 // 5
24 // 5
25 // 5
Try each of the following in your interactive shell. What pattern do you notice?
0 % 2
1 % 2
3 % 2
4 % 2
5 % 2
6 % 2
20 % 5
21 % 5
22 % 5
23 % 5
24 % 5
25 % 5
Write down in your notes:
// and /?// and %?Try each of the following in your interactive shell.
23 // 5.5
23 / 0
Write down in your notes:
Example: Let's say I'm programming a super computer with 64 processors to perform 1500 variations of a simulation for a physics experiment, and each of the simulations takes about the same amount of time to run. How many simulations should be given to each processor?
num_processors = 64
num_simulations = 1500
simulations_per_processor = num_simulations // num_processors
leftover_simulations = num_simulations % num_processors
print("Each processor should get",simulations_per_processor,"simulations")
print("and",leftover_simulations,"processors will each get one extra")
Modulo is also good if you need to check if a number is even or odd
253 % 2 #odd numbers have a remainder of 1 when divided by 2
254 % 2 #even numbers have a remainder of 0 when divided by 2
Or, if you want to check if a number is divisible by 4 - say you're checking to see if the year is a presidential election year, Olympic year, leap year, etc., you can see if the result is 0
2024 % 4