Python as a calculator: the seven operators, and the order it applies them in.
| Operator | Meaning | Example |
|---|---|---|
| + - * | add, subtract, multiply | 10 * 5 → 50 |
| / | division, always a float | 10 / 5 → 2.0 |
| // | floor division: round down | 10 // 3 → 3 |
| % | modulus: the remainder | 10 % 3 → 1 |
| ** | power | 2 ** 3 → 8 |
# addition
10 + 5
# ans: 15
# subtraction
10 - 5
# ans: 5
# multiplication
10 * 5
# ans: 50
# division (always returns float)
10 / 5
# ans: 2.0
10 / 3
# ans: 3.3333...
# floor division
10 // 3
# ans: 3
Floor division keeps the whole part: 10 / 3 is 3.33…, rounded down to 3.
# modulus (remainder)
10 % 3
# ans: 1
7 % 3
# ans: 1
15 % 4
# ans: 3
Make as many full groups as you can; the modulus is what is left over.
# power/exponentiation
10 ** 2
# ans: 100
2 ** 3
# ans: 8
5 ** 0
# ans: 1
# PEMDAS rules apply
10 + 5 * 2
# ans: 20 (multiply first)
(10 + 5) * 2
# ans: 30 (parentheses first)
2 + 3 * 4
# ans: 14
Parentheses, then **, then * / // %, then + -. The highlighted part runs next.
Work each one out before pressing →.
# what is the result?
7 % 3
# ans: 1
# division types
10 / 3
# ans: 3.3333...
10 // 3
# ans: 3
# negative modulus?
-10 % 3
# ans: 2
# what is this?
2 ** 3 ** 2
# ans: 512 (right associative: 2^(3^2) = 2^9)
# operator precedence?
10 + 5 * 2
# ans: 20
# what happens?
5 / 0
# ans: ZeroDivisionError
# floor division with negative?
-10 // 3
# ans: -4
# modulus with float?
10.5 % 3
# ans: 1.5
# what is result?
100 // 10
# ans: 10
# power of zero?
5 ** 0
# ans: 1
# negative exponent?
2 ** -1
# ans: 0.5
# order of operations?
2 * 3 ** 2
# ans: 18 (exponent first)
# mixing operations?
10 - 5 + 3
# ans: 8 (left to right)
# division by float?
10 / 2.0
# ans: 5.0
/ vs /// always gives a float; // rounds down, even for negatives (-10 // 3 is -4).
% is the remainderWhat is left after making as many full groups as possible.
Parentheses, **, then * / // %, then + -; equal ranks go left to right, except **.
5 / 0 raises ZeroDivisionError.