Python Operators & operator precedence: 8 practice problems
UNIT 1 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise Operators & operator precedence nowAll topicsTheory: Operators & operator precedence in Python
THEORY
------
OPERATOR FAMILIES
Arithmetic + - * / // % **
Comparison == != < > <= >= (result: bool; can be CHAINED: a < b < c)
Logical and or not
Assignment = += -= *= /= //= %= **= (also walrus := in expressions)
Bitwise & | ^ ~ << >> (work on the binary digits of ints)
Membership in, not in ("a" in "cat", 3 in [1, 2, 3])
Identity is, is not (same OBJECT? use for None: x is None)
PRECEDENCE (high -> low) — "PEMDAS plus extras"
1. () parentheses
2. ** power RIGHT-associative: 2 ** 3 ** 2 = 2 ** 9 = 512
3. +x -x ~x unary -3 ** 2 = -(3 ** 2) = -9 (** beats unary minus)
4. * / // % multiplicative left to right: 17 % 5 * 2 = (17 % 5) * 2 = 4
5. + - additive 10 - 2 - 3 = (10 - 2) - 3 = 5
6. << >> shifts
7. & bitwise AND
8. ^ bitwise XOR
9. | bitwise OR
10. in, not in, is, is not, <, <=, >, >=, !=, == comparisons (all same level, chain)
11. not
12. and
13. or
(lowest: conditional expression x if c else y, lambda, :=)
CLASSIC TRAPS
flags & 4 != 0 means flags & (4 != 0) -> flags & True — WRONG! write (flags & 4) != 0
a + b / 2 divides only b
-7 // 2 = -4 (floor goes DOWN), -7 % 2 = 1 (result takes the sign of the divisor)
BITWISE CHEAT SHEET (6 = 110, 3 = 011)
6 & 3 = 2 (010) 6 | 3 = 7 (111) 6 ^ 3 = 5 (101) ~6 = -7 1 << 3 = 8 16 >> 2 = 4
n & (n - 1) clears the lowest 1-bit -> == 0 exactly when n is a power of two (n > 0)
8 Operators & operator precedence practice problems
1. Predict 13 Expressions — return a list of your PREDICTED values (literals):
Medium1 way to solve📤 OUTPUT: return a list of your 13 predicted values. Use `return`, not print().
a) 3 + 4 * 2 ** 2 b) (3 + 4) * 2 ** 2 c) 2 ** -1
d) 17 % 5 * 2 e) 100 // 7 % 4 f) -3 ** 2
g) 5 > 3 > 1 h) 1 < 2 == 2 i) True + True
j) 7 & 3 | 8 k) 10 - 2 - 3 l) 2 * 3 % 4
m) not 1 or 0 and 5
Example format: return [19, ...]
Solve “Predict 13 Expressions — return a list of your PREDICTED values (literals):” in your browser →2. Memory Block Sizes — bitwise trick
Easy3 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Real world: Memory allocators use block sizes 1, 2, 4, 8, 16 ... bytes.
is_power_of_two(16) -> True is_power_of_two(18) -> False is_power_of_two(0) -> False
Ways: n > 0 and n & (n - 1) == 0 (careful with precedence!) · loop dividing by 2
Solve “Memory Block Sizes — bitwise trick” in your browser →3. Linux File Permissions — & with parentheses
Easy2 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Real world: rwx permissions are bits: READ = 4, WRITE = 2, EXEC = 1. 7 = rwx, 5 = r-x.
Return True if `permission` bit is set in `flags`.
has_permission(5, 4) -> True has_permission(5, 2) -> False
Solve “Linux File Permissions — & with parentheses” in your browser →4. Projectile Landing — quadratic formula
Medium2 ways to solve📤 OUTPUT: return a tuple, e.g. (1.0, 2.0). Use `return`, not print().
Real world: When does a thrown ball hit the ground? Solve ax² + bx + c = 0.
Return a tuple of REAL roots sorted ascending, rounded to 2: two roots, one root (when
discriminant is 0, return a 1-tuple), or an empty tuple () when no real roots. a != 0.
quadratic_roots(1, -3, 2) -> (1.0, 2.0)
quadratic_roots(1, 2, 1) -> (-1.0,)
quadratic_roots(1, 0, 1) -> ()
Solve “Projectile Landing — quadratic formula” in your browser →5. Road Trip Average Speed — the "average of averages" trap
Easy1 way to solve📤 OUTPUT: return a float, e.g. 40.0. Use `return`, not print().
Real world: You drive d1 km in t1 hours, then d2 km in t2 hours. Average speed?
It's total distance / total time (NOT the mean of the two speeds). Round to 2.
average_speed(60, 1, 60, 2) -> 40.0
Solve “Road Trip Average Speed — the "average of averages" trap” in your browser →6. School Trip Buses — ceiling division without math.ceil
Easy3 ways to solve📤 OUTPUT: return an int, e.g. 4. Use `return`, not print().
Real world: 125 students, 40 seats per bus -> 4 buses.
buses_needed(125, 40) -> 4 buses_needed(120, 40) -> 3 buses_needed(0, 40) -> 0
Ways: -(-a // b) · (a + b - 1) // b · a // b + (a % b > 0) (bool adds as 0/1!)
Solve “School Trip Buses — ceiling division without math.ceil” in your browser →7. Repository Permissions — interview at a code-hosting company
Project1 way to solve📤 OUTPUT: return a tuple, e.g. (1, ['READ']). Use `return`, not print().
Interviewer: "A user can have several roles. Compute their effective permissions as ONE bitmask."
Permissions: READ=1, WRITE=2, DELETE=4, ADMIN=8. Each role's bits are in ROLE_BITS (above).
mask = bitwise OR of all the user's roles (unknown roles are ignored).
Return (mask, names) where names lists the permissions set, in the order READ, WRITE, DELETE, ADMIN.
access_summary(["editor", "viewer"]) -> (3, ["READ", "WRITE"])
Solve “Repository Permissions — interview at a code-hosting company” in your browser →8. Stage 4 — Shunting-Yard: operator PRECEDENCE becomes Reverse Polish order
Compiler1 way to solve📤 OUTPUT: return a list of token strings, e.g. ['1', '2', '3', '*', '+']. Use `return`, not print().
tokens: list of strings (numbers, names, + - * / // % **, "(", ")"). Return the RPN list.
Precedence: ** (3, RIGHT-associative) > * / // % (2) > + - (1). Others are left-associative.
Mismatched parentheses -> raise SyntaxError("mismatched parentheses")
to_rpn(["1", "+", "2", "*", "3"]) -> ["1", "2", "3", "*", "+"]
Solve “Stage 4 — Shunting-Yard: operator PRECEDENCE becomes Reverse Polish order” in your browser →