Course outline · 0% complete

0/32 lessons0%

Course overview →

Arithmetic, Precisely

lesson 1-3 · ~11 min · 3/32

Seven operators

Arithmetic is the part of Python you will use in literally every program, and the three unfamiliar operators at the bottom of this table are the ones working code leans on: // and % split totals into units (seconds into minutes, items into pages), and % powers every is-it-divisible and wrap-around check you will ever write.

Python has seven arithmetic operators. The first four are familiar, the last three do the heavy lifting in real programs:

OperatorMeaningExampleResult
+add7 + 310
-subtract7 - 34
*multiply7 * 321
/divide7 / 23.5
//floor divide (drop the remainder)7 // 23
%modulo (the remainder)7 % 21
**power2 ** 101024

Two things to burn in now. First, / always produces a float, even 10 / 5 gives 2.0. Second, // and % come as a pair: // answers how many whole times does it fit and % answers what is left over. n % 2 == 0 is the classic even-number test.

Code exercise · python

Run this and compare each result to the table above. Pay special attention to the difference between `/` and `//`.

Order of operations

Python follows math class: ** first, then * / // %, then + -. Operators at the same level run left to right.

8 + 2 * 3      # 14, not 30
(8 + 2) * 3    # 30, parentheses win

When an expression is not instantly obvious, add parentheses. They cost nothing and make the intent visible.

Quiz

What does `17 // 5` evaluate to?

Code exercise · python

Your turn. A movie is `200` minutes long. Use `//` and `%` to split that into hours and leftover minutes, then print them like `3 h 20 min` (using commas in print).

Code exercise · python

Run the wrap-around pattern, the second big job of `%`. Values that cycle (clock hours, days of the week) wrap by taking the remainder: 9 o'clock plus 5 hours is `(9 + 5) % 12`, which is 2 o'clock. Day 6 (Saturday) plus 3 days is day `(6 + 3) % 7`, Tuesday.

Problem

Without running it, evaluate this expression the way Python does: `8 + 2 * 3 ** 2`. What number results?