Foundations · #2 of 11

Operators + Boolean Logic

Comparison, identity, and truth

Why it matters

Decision-making and loops rely on booleans. One wrong comparison breaks everything.

The idea

Operators turn expressions into new values. == checks equality of values, is checks identity (same object in memory). For literals, 1 == 1.0 is True but 1 is 1.0 is False.

Arithmetic operators

| Operator | Meaning | | --- | --- | | + | add | | - | subtract | | * | multiply | | / | divide (float) | | // | floor divide | | % | remainder | | ** | power |

/ always returns a float (6 / 2 == 3.0); use // when you want an integer quotient. % gives the remainder — the workhorse of "is this even?" and cyclic-index problems.

Try it

Truthiness in Python: 0, "", [], {}, None are all falsy. Everything else is truthy.

for v in [0, 1, "", "hi", [], [0], None, {}, {"k": 0}]:
  print(repr(v), "->", bool(v))
not loaded

Short-circuit evaluation: and returns the first falsy operand (or the last value); or returns the first truthy.

print(0 or "fallback")   # 'fallback'
print(5 or "fallback")   # 5
print(0 and "blocked")   # 0
print(5 and "passed")    # 'passed'
not loaded

Identity vs equality bites in real code:

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)   # True  — same values
print(a is b)   # False — different objects
c = a
print(a is c)   # True  — same object
not loaded

Quick check

Mini drills

Do's and don'ts

Common mistakes

Key takeaways