Part 1 of 6 · Chapter 4 of 4

Arithmetic, and Where It Surprises You

Two slashes and one slash look like a typo of each other, and they hand back different types on purpose. Divide the same two numbers both ways and see exactly where a float appears uninvited.

Beginner8 min read

Two slashes and one slash look like a typo of each other. They are not — they answer two different questions, and confusing them is one of the most common bugs a beginner writes without noticing.

Two kinds of division

Terminal
$ >>> 7 / 2$ 3.5$ >>> 7 // 2$ 3

/ is true division— it answers “what is 7 divided by 2, exactly?” and always returns a float, even when the numbers divide evenly. // is floor division— it answers “how many whole times does 2 go into 7?” and rounds the result down. Use // when the question is really about a count, like splitting 7 items into groups of 2.

Try an expression

>>> 7 / 2

3.5

type: float

The order operations actually run in

Python follows the order you were taught in school — exponents, then multiplication and division, then addition and subtraction — with one addition: ** is exponentiation, and it binds tighter than everything else.

Terminal
$ >>> 2 + 3 * 4$ 14$ >>> 2 ** 3 * 4$ 32

When an expression gets more than two operators deep, add parentheses even where they are not required. (2 + 3) * 4 costs you two characters and removes any question of what the next reader thinks runs first.

Where an int quietly becomes a float

Whole numbers in Python are int. Numbers with a decimal point are float. Mixing them in one expression is allowed, and Python resolves it by upgrading the int — the result comes back as a float, even if the value looks whole.

Terminal
$ >>> 6 / 3$ 2.0$ >>> type(6 / 3)$ <class 'float'>

Key takeaways

  • / is true division and always returns a float. // is floor division and rounds down.
  • ** is exponentiation, and it binds tighter than * and + — add parentheses rather than rely on memory.
  • Mixing an int and a float in one expression upgrades the whole result to a float.
  • Never compare floats with == after arithmetic. 0.1 + 0.2 == 0.3 is False.