Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

2.5 Dividing integers

Learning objectives

By the end of this section you should be able to

  • Evaluate expressions that involve floor division and modulo.
  • Use the modulo operator to convert between units of measure.

Division and modulo

Python provides two ways to divide numbers:

  • True division (/) converts numbers to floats before dividing. Ex: 7 / 4 becomes 7.0 / 4.0, resulting in 1.75.
  • Floor division (//) computes the quotient, or the number of times divided. Ex: 7 // 4 is 1 because 4 goes into 7 one time, remainder 3. The modulo operator (%) computes the remainder. Ex: 7 % 4 is 3.

Note: The % operator is traditionally pronounced "mod" (short for "modulo"). Ex: When reading 7 % 4 out loud, a programmer would say "seven mod four."

Unit conversions

Division is useful for converting one unit of measure to another. To convert centimeters to meters, a variable is divided by 100. Ex: 300 centimeters divided by 100 is 3 meters.

Amounts often do not divide evenly as integers. 193 centimeters is 1.93 meters, or 1 meter and 93 centimeters. A program can use floor division and modulo to separate the units:

  • The quotient, 1 meter, is 193 // 100.
  • The remainder, 93 centimeters, is 193 % 100.

Programs often use floor division and modulo together. If one line of code floor divides by m, the next line will likely modulo by m. The unit m by which an amount is divided is called the modulus. Ex: When converting centimeters to meters, the modulus is 100.