Python for Programmers: Two Division Operators
Welcome to the Two Division Operators lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Python gives us integers and floats, and it tries to help us avoid mixing them up. For example, Python has two separate division operators: standard division and integer division. These operators are separate because dividing integers doesn't always result in a round number.
>
5 / 2Result:
2.5
The basic division operator
/always returns floats, even when dividing two integers that result in a round number.>
4 / 2Result:
2.0
This isn't the case with
*,+, and-. When we use those operators on two integers, we always get a round number back, so we can represent the result as an integer.>
25 * 10Result:
250
Python's other division operator is integer division,
//, sometimes called "floored quotient." This divides the numbers, but only gives us the whole number component of the result, rounded down (or "floored").>
7 / 2Result:
>
7 // 2Result:
>
4 // 2Result:
2
>
5 // 2Result:
2
The
//operator works in the same way with floats: it gives us a floored float. But note that floats are still inherently imprecise, and the//operator can't change that! (A different lesson will show floating point imprecision in more detail.)>
5.0 // 2Result:
2.0
>
5 // 2.0Result:
2.0
You may wonder why Python has two division operators, or why it draws a distinction between integers and floats in the first place. Other languages, most notably JavaScript, demonstrate that neither of those is strictly necessary. JavaScript only has floats (which it simply calls "numbers"), and it only has one division operator.
We separate integers and floats because different problems call for different kinds of numbers. When indexing into arrays (which Python calls "lists") we don't want to worry about whether the
iinsome_list[i]is actually1.2. We always use integers for list indexes.If we're writing a game, we might need to represent coordinates in 2D or 3D space: "the player is at coordinate
(2.162, 92.816)". But we also need the code to be fast, and it's OK if the player's position in the game world is off by 0.00000000000000004. Floating point is perfect for this: it's very fast, it's a "real number" data type with a decimal point, and its imprecision doesn't matter in this case.Python has more number types than just these two. It also has complex numbers, decimals, and fractions. These are much less common, and used only in specialized situations. For most code, ints and floats are sufficient.