Skip to content
CodeNest

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 %.

Python
Output
22
12
85
3.4
3
2
289
— expected output; press Run to execute it yourself

Why % matters

The remainder operator answers "what is left over?", and it turns up everywhere:

  • n % 2 == 0 tests whether n is even
  • n % 3 == 0 tests divisibility by 3
  • total % 60 converts a second count into leftover seconds
  • n % 10 extracts the last digit of a number
Python
Output
62 min 5 sec
4
False
— expected output; press Run to execute it yourself

Precedence

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.

Python
Output
14
20
512
-9
— expected output; press Run to execute it yourself

Shorthand 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 **=.

Python
Output
34
— expected output; press Run to execute it yourself

Exercise

You have total_minutes = 500. Compute hours (whole hours) and mins (leftover minutes) using // and %, then print them as 8h 20m.

Python
Output

Press Run to execute this code.

Check your understanding

0/3 answered
  1. 1.What is 7 // 2?
  2. 2.What is 10 % 3?
  3. 3.What is the value of 2 + 3 * 4 ** 2?