Conditionals & Truthy Logic
Master Python conditional flow with if, elif, and else, and discover how Python evaluates the inherent truth value of any data structure.
Indentation-Based Control Flow
Python controls conditional execution using if, elif (short for else-if), and else statements. Code blocks are delineated strictly by consistent 4-space indentation rather than curly braces or keywords.
An if statement evaluates a condition. If the condition is truthy, the indented suite of code executes. If false, Python checks any subsequent elif branches in sequence until one matches, or falls back to the optional else block.
Python also offers a concise ternary conditional expression for inline assignments: status = 'adult' if age >= 18 else 'minor'.
The Pythonic Truthy and Falsy Model
In Python, every object has an inherent boolean truth value. You do not need to convert objects explicitly with bool(x) inside conditional checks.
By standard definition (PEP 8 and the Python Data Model), the following values are considered falsy:
Constants: None and False.
Numeric zeros: 0, 0.0, 0j, and Decimal(0).
Empty sequences and collections: empty string "", empty list [], empty tuple (), empty dictionary {}, and empty set set().
All other objects - including non-empty collections, non-zero numbers, and custom objects that do not define a zero length - evaluate to truthy.
Writing Idiomatic Python Conditionals
Write concise, idiomatic checks by relying on natural truthiness: write if items: instead of if len(items) > 0:, and write if not items: to check for an empty collection.
When evaluating boolean flags, write if is_ready: rather than if is_ready == True:. Redundant equality checks are un-pythonic and can introduce subtle type conversion bugs.
The Truthy/Falsy Junction
Feed different Python values into the conditional gate. Watch how the boolean evaluation pipe automatically routes objects to either the if or else branch.
Python Rule: Never write if len(items) > 0: or if val == True:. Python natively evaluates sequences and values directly for their truthiness (if items:).
Empty collections ([], {}, set(), ()) have length 0 and evaluate to False.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Code blocks in Python are defined by 4-space indentation, not braces.
- Empty collections, numeric zeros, None, and False are all inherently falsy.
- Prefer 'if items:' over 'if len(items) > 0:' for readability.
- Use 'if val is not None:' when numeric zero or empty strings are valid data.
- Ternary expressions use the syntax: true_val if condition else false_val.
Done with this concept?
Mark it complete to track your progress. No login needed.