Division Operators

CS 65: Introduction to Computer Science I

Floating-point division operator

The / operator will always give you a float as a result.

In [1]:
320 / 20
Out[1]:
16.0
In [2]:
403.0 / 24.0
Out[2]:
16.791666666666668

Integer division operators

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.

In [3]:
320 // 20
Out[3]:
16
In [4]:
403 // 24
Out[4]:
16

Modulo operator

The % operator is the modulo operator - another word for remainder - it will ignore the quotient and just give you the remainder.

In [5]:
403 // 24
Out[5]:
16
In [6]:
403 % 24
Out[6]:
19

Group Exercises

Try each of the following in your interactive shell. What pattern do you notice?

In [ ]:
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?

In [ ]:
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:

  • What is the difference between // and /?
  • What is the difference between // and %?

Try each of the following in your interactive shell.

In [ ]:
23 // 5.5
23 / 0

Write down in your notes:

  • What happens when you use a float with the floor division operator?
  • What happens in Python if you try to divide by 0?

When is this useful?

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?

In [8]:
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")
Each processor should get 23 simulations
and 28 processors will each get one extra

Modulo is also good if you need to check if a number is even or odd

In [7]:
253 % 2 #odd numbers have a remainder of 1 when divided by 2
Out[7]:
1
In [9]:
254 % 2 #even numbers have a remainder of 0 when divided by 2
Out[9]:
0

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

In [10]:
2024 % 4
Out[10]:
0