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))
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'
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
Quick check
- Q: When should you use
is? A: Identity checks (likex is None).
Mini drills
- Check if a number is even using
%. - Test if a character exists in a string.
Do's and don'ts
- Do use
x is NoneforNonechecks. - Don't use
isto compare strings or numbers.
Common mistakes
- Mistake: Using
isinstead of==. Fix: Use==for value equality. - Mistake:
if x = 3. Fix: Use==in conditions.
Key takeaways
==compares value;iscompares identity.- Short-circuit operators are useful for defaulting (
x or 0). - Falsy values:
0,"",[],{},None,set(). - Never compare to
True/Falseexplicitly — just use the value.