Introduction
Conditionals and loops are the building blocks of any program's logic. Python's versions are clean and readable by design, and they include a few unique features -- like the loop else clause -- that you will not find in most other languages.
Key Concepts
if/elif/else: Branch execution based on boolean conditions.- Ternary expression:
value_if_true if condition else value_if_false-- a one-line conditional. forloop: Iterates directly over any iterable (list, range, dict, file, etc.).whileloop: Repeats as long as a condition is truthy.- Loop
elseclause: Runs when a loop finishes without hittingbreak.
Real World Context
Every request handler, data pipeline, and CLI tool relies on conditionals and loops. The loop else clause is a Python-specific pattern that simplifies search-and-not-found logic without extra boolean flags. Mastering break, continue, and else lets you write control flow that is both concise and immediately clear to other developers.
Deep Dive
Conditional Statements
pythonif condition: # runs if condition is truthy elif other_condition: # runs if first was false and this is true else: # runs if all above were false
Ternary Expression
pythonresult = "yes" if condition else "no" # Chained ternary (use sparingly) grade = "A" if score >= 90 else "B" if score >= 80 else "C"
For Loops
Iterate over any iterable:
python# Over a list for item in [1, 2, 3]: print(item) # With index using enumerate for i, item in enumerate(["a", "b", "c"]): print(f"{i}: {item}") # Over a range for i in range(5): # 0, 1, 2, 3, 4 print(i) # Over dictionary items for key, value in d.items(): print(f"{key}: {value}")
While Loops
pythonwhile condition: # runs while condition is truthy if should_exit: break if should_skip: continue
Loop Else Clause
The else block runs if the loop completes without break:
pythonfor item in items: if item == target: print("Found!") break else: print("Not found") # Only if loop didn't break
Common Pitfalls
- Chaining too many ternary expressions --
a if x else b if y else cis hard to read. Use a regularif/elif/elseblock when you have more than two branches. - Modifying a collection during iteration -- Deleting or inserting items while looping over a list causes skipped elements or
RuntimeErrorwith dicts. Iterate over a copy or build a new collection. - Confusing loop
elsewith conditionalelse-- The loopelseruns when the loop exits normally (nobreak), not when the loop body is "false." Think of it as "no break."
Best Practices
- Use
forloops overwhileloops when the iterable is known --for item in itemsis clearer and less error-prone than manually managing an index withwhile. - Use
enumerateinstead ofrange(len(...))-- It pairs each element with its index, eliminating off-by-one errors.
Summary
- Python's
if/elif/elseand ternary expressions handle all branching needs. forloops iterate directly over iterables;whileloops repeat until a condition is false.- The loop
elseclause runs only when the loop completes withoutbreak-- useful for search patterns. - Avoid modifying collections during iteration and keep ternary chains short.
- Prefer
forwithenumerateoverwhilewith manual index tracking.
Code Examples
python
# Common patterns
numbers = [1, 2, 3, 4, 5]
# Find first match
for n in numbers:
if n > 3:
result = n
break
else:
result = None
# Enumerate with start index
for rank, player in enumerate(players, start=1):
print(f"#{rank}: {player}")