Control Structures
Control structures: everything that decides between "do this" and "do that".
You can store numbers, text, and true-or-false values in variables — but so far, your programs run top-to-bottom, one line after the next. Like reading a shopping list out loud.
What if the program should greet teenagers differently from adults? What if it should process a thousand data points without you writing a thousand lines? Control structures solve both problems: conditionals let code choose a path, and loops let code repeat. By the end of this article, you will understand the three fundamental patterns — if/elif/else, for, and while — and know exactly when to use which one.
Branching — Making Decisions with If/Elif/Else
Definition
What is branching?
Analogy
Definition
The analogy breaks at one point: a human bouncer uses judgment and gray areas ("looks old enough," "forgot their ID"). A program knows only True or False — the condition age >= 18 is either met or not, with no in-between.
Note
Execution trace: age = 17
- 1. Read input: age = 17
- 2. Check age >= 18 → False → skip block
- 3. Check age >= 16 → True → execute block: "Soft drinks only"
- 4. else is skipped entirely — exactly one path was taken
Notice: the else block is never reached here because elif already matched. Exactly one path is always taken.
Code example: Age checker
age = int(input("How old are you? "))
if age >= 18:
print("Welcome!")
elif age >= 16:
print("Soft drinks only.")
else:
print("Sorry, too young.")Caution
Common misconception: "if checks all conditions"
Wrong! In an if/elif/else chain, Python checks only until the first True condition. All subsequent branches are skipped entirely, even if their conditions would also be True.
Watch the order: if you write age >= 16 before age >= 18, even 20-year-olds end up in the "soft drinks" block, because >= 16 is True for them and gets checked first.
For Loops — Repeating a Known Number of Times
Definition
What is a for loop?
Analogy
Definition
The analogy breaks where a real carrier might skip a house or take a shortcut. A for loop visits every element by default — unless you explicitly use break to exit or continue to skip the current iteration.
Note
Code examples: Lists and range()
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(fruit)
# Output (one value per line): Apple, Banana, Cherryrange(n) generates the numbers 0 through n-1 — exactly n iterations, but the end value itself is never reached:
for i in range(5):
print(i)
# Output (one value per line): 0, 1, 2, 3, 4 (not 1 to 5!)The extended form range(start, stop, step) gives full control over the start, end, and step size:
for i in range(1, 10, 2):
print(i)
# Output (one value per line): 1, 3, 5, 7, 9 (odd numbers)Caution
Common misconception: "range(5) gives 1 to 5"
range(5) starts at 0 and stops before 5 — producing 0, 1, 2, 3, 4. This half-open interval is the most common beginner pitfall with for loops. But it fits perfectly with zero-based indexing: range(len(my_list)) produces exactly all valid positions.
While Loops — Repeating Until Something Changes
Definition
What is a while loop?
Analogy
Definition
In real life, you would eventually give up if someone never types the right password. A while loop never gives up on its own — it runs until the condition becomes False or you exit with break, no matter how long that takes.
Note
Code examples: Counter and while True
counter = 0
while counter < 5:
print(f"Iteration {counter}")
counter += 1
# Output (one value per line): Iteration 0, 1, 2, 3, 4counter starts at 0 and increases by 1 each iteration. Once counter reaches 5, the condition counter < 5 is no longer True, and the loop exits. Without counter += 1, counter would stay at 0 forever — an infinite loop.
while True:
user_input = input("Type 'exit' to quit: ")
if user_input == "exit":
break
print("Program ended.")while True intentionally creates an infinite loop. The break statement exits it in a controlled way once the desired condition occurs. This pattern is a legitimate tool in servers, games, and interactive programs — not a bug.
Caution
Warning: Infinite Loops
If the variable in the condition never changes or the condition always remains True, the loop runs forever and blocks your program.
Emergency exit: Press Ctrl+C to stop a stuck program in the terminal.
Caution
Common misconception: "Infinite loops are always bugs"
Many real programs intentionally run in a while-True loop: servers wait for requests, games update the screen, and GUIs respond to events. The difference between bug and feature is whether the loop has a controlled exit point (break at a defined event).
For vs. While — Choosing the Right Tool
Known number of iterations. Iterates over collections or range(). Typical: traversing lists, fixed repetitions.
Unknown number of iterations. Checks condition before each pass. Typical: user input, waiting for events.
Rule of thumb: "Do I know how many times?" → for. "Do I know when to stop?" → while.
Interactive: Which Control Structure Do I Need?
Answer the questions in the decision tree to find the right control structure for your problem. Notice how the questions use exactly the criteria from the previous sections: Known count? Condition? Multiple cases?
Python uses indentation (usually 4 spaces per level) instead of curly braces. All lines in a block must be indented identically. A misindented print() can end up running every time instead of only inside the if block — with no error message at all.
If you mix tabs and spaces so that the meaning depends on how wide a tab is (for example within the same block), Python 3 raises a TabError (a special subclass of IndentationError). Python catches this immediately — the error is reported right away, not silently ignored. Style guides recommend using 4 spaces consistently. Most editors can be configured so that the Tab key automatically inserts 4 spaces.
Decision guide: If you want to process a fixed set of elements (a list, a range of numbers), use for. If you are waiting for an event or do not know how many iterations are needed (user input, data stream), use while.
Preview: Loops can also be nested — a loop inside a loop (e.g., rows times columns in a grid). This concept becomes important when working with two-dimensional data structures.
Note
Key Takeaways
- if/elif/else evaluates conditions top-to-bottom and executes exactly one branch — the first one that is True. Order matters.
- A for loop walks through every element of a sequence or range(). For lists and range(), the number of iterations is fixed before the loop starts.
- A while loop repeats as long as its condition is True. If nothing inside the loop ever makes the condition False, the loop runs forever.
- for = "I know how many times." while = "I don't know how many times, but I know when to stop."
- Python uses indentation to define code blocks. Getting the whitespace wrong changes what your program does — or breaks it entirely.
Check
Quiz: Control Structures
A colleague uses three separate if statements instead of an if/elif/else chain for the same conditions. What is the key difference?
Select one answer
1. A colleague uses three separate if statements instead of an if/elif/else chain for the same conditions. What is the key difference?
2. What does range(2, 8) produce?
3. x = 10. Which block runs? if x > 20: print("A") elif x > 5: print("B") elif x > 0: print("C") else: print("D")
4. A program should repeatedly ask the user for numbers until they type "stop". Which loop type fits best?
Check
Comprehension Check
Can you explain this in your own words? Tick what you've got.
0 of 3 done