FoundationsLesson 3 of 1912 min
Numbers and Operators
Arithmetic, integer division, remainders, powers, and the precedence rules that decide what runs first.
By the end you will be able to
- Use +, -, *, /, //, %, and ** correctly
- Predict whether a result is an int or a float
- Use % to test divisibility and extract digits
Python's arithmetic operators look familiar, with two that are worth real attention: // and %.
22
12
85
3.4
3
2
289
— expected output; press Run to execute it yourselfWhy % matters
The remainder operator answers "what is left over?", and it turns up everywhere:
n % 2 == 0tests whethernis evenn % 3 == 0tests divisibility by 3total % 60converts a second count into leftover secondsn % 10extracts the last digit of a number
62 min 5 sec
4
False
— expected output; press Run to execute it yourselfPrecedence
Python follows standard mathematical precedence: ** first, then * / // %, then + -. Operators at the same level run left to right.
Parentheses override all of it, and are almost always clearer than relying on the table.
14
20
512
-9
— expected output; press Run to execute it yourselfShorthand assignment
Updating a variable using its own value is so common it has a shorthand. x += 3 means exactly x = x + 3, and the same pattern works for -=, *=, /=, //=, %=, and **=.
34
— expected output; press Run to execute it yourselfExercise
You have total_minutes = 500. Compute hours (whole hours) and mins (leftover minutes) using // and %, then print them as 8h 20m.
Press Run to execute this code.