Operators
Arithmetic, comparison, logical, and assignment operators — the building blocks of every expression.
Arithmetic operators
print(7 + 3) # 10 addition
print(7 - 3) # 4 subtraction
print(7 * 3) # 21 multiplication
print(7 / 3) # 2.333... true division, always returns a float
print(7 // 3) # 2 floor division, rounds down to an int
print(7 % 3) # 1 modulo, the remainder
print(7 ** 3) # 343 exponentiation
// and % are a pair worth memorizing together: a == (a // b) * b + (a % b) always holds.
Comparison operators
==, !=, <, >, <=, >= compare values and always return a bool. Note == checks value equality, not identity — use is only when you specifically mean "the same object in memory" (most commonly x is None).
print(5 == 5.0) # True -- same value, different types, still equal
print([1, 2] == [1, 2]) # True -- lists compare element by element
Logical operators
and, or, not combine boolean expressions. Python short-circuits: a and b skips evaluating b if a is already falsy, and a or b skips b if a is already truthy.
subscribers = 250000
is_verified = True
if subscribers > 100000 and is_verified:
print("Eligible for the Play Button")
Assignment operators
views = 100
views += 50 # same as views = views + 50
views *= 2 # same as views = views * 2
print(views) # 300
Operator precedence
Python follows standard math precedence: ** first, then * / // %, then + -, then comparisons, then not, then and, then or. When in doubt, use parentheses — they cost nothing and remove ambiguity for whoever reads the code next.
- •/ always returns a float (true division); // floors the result to an int (floor division).
- •== compares values; is compares identity (same object) — use is only for things like x is None.
- •and/or short-circuit: the second operand is only evaluated if the first doesn't already decide the result.
- •a == (a // b) * b + (a % b) always holds — floor division and modulo are a matched pair.
- •When precedence gets unclear, add parentheses — it costs nothing and removes ambiguity.
Arithmetic and short-circuiting
Revision Flashcards
Tap a card to flip it and see the answer.