Python If/Else and Boolean Logic Tracing
Conditional statements steer program execution based on boolean truth values. Python's short-circuit evaluation rules (`and` / `or`) and ternary conditional expressions (`x if cond else y`) are frequently tested in coding assessments to verify control flow comprehension.
Core Conceptual Insights
Theoretical Blueprint:An if/elif/else chain is like a train track switch yard. A train travels down only the very first branch track whose switch condition checks green (`True`); all subsequent branch tracks are bypassed.
Common Developer Trap:Beginners often forget that in Python, empty collections (`[]`, `''`, `{}`) and `0` evaluate to `False` in boolean contexts (`falsy`).
Structured Practice Breakdown
Short-circuit `or` evaluation
def log(name, val):
print(name, end=' ')
return val
res = log('A', False) or log('B', True) or log('C', True)
print(f'-> {res}')A B -> TrueExecution Walkthrough
Python evaluates `log('A', False)` (`prints 'A '`, returns `False`). Since `False or ...` must keep checking, it evaluates `log('B', True)` (`prints 'B '`, returns `True`). Since `True or ...` short-circuits, `log('C', True)` is skipped. Output: `A B -> True`.
Short-circuit `and` returning actual value
val = [10] and 'Python' and 42 print(val)
42Execution Walkthrough
`[10]` is truthy, so `and` checks `'Python'`. `'Python'` is truthy, so `and` checks `42`. Since `42` is truthy and the last item, `42` is returned directly.
Nested conditional ternary expression
score = 85
grade = 'A' if score >= 90 else ('B' if score >= 80 else 'C')
print(grade)BExecution Walkthrough
Since `85 >= 90` is False, execution moves to `('B' if score >= 80 else 'C')`. Because `85 >= 80` is True, `'B'` is returned.
Elif precedence ordering
x = 15
if x % 3 == 0:
print('Fizz')
elif x % 5 == 0:
print('Buzz')
elif x % 15 == 0:
print('FizzBuzz')FizzExecution Walkthrough
Even though `15` is divisible by `5` and `15`, the top `if x % 3 == 0:` checks True first, printing `'Fizz'` and exiting the conditional chain immediately.