Control Structures

Control structures: everything that decides between "do this" and "do that".

Fundamentals 12 min Beginner April 26, 2026

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

What is branching?

AnalogyDefinition
Imagine a bouncer at a club entrance. They check your age against a set of rules from top to bottom: 18 or older — full entry. 16 or older — soft drinks only. Everyone else — turned away. Once a rule matches, the rest are irrelevant.

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.

== equal to
!= not equal to
< less than
> greater than
<= less than or equal
>= greater than or equal
and both must be True
or at least one must be True
not reverses the truth value

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: even though age = 17 would also satisfy the else condition, the else block is never reached 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.")

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

What is a for loop?

AnalogyDefinition
A mail carrier with a list of 10 addresses knows the exact number of stops before leaving the post office and visits each one in order. Similarly, a for loop knows its iteration count before it starts.

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.

Code examples: Lists and range()

fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
    print(fruit)
# Output: Apple, Banana, Cherry

range(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: 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: 1, 3, 5, 7, 9  (odd numbers)

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 mistake 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

What is a while loop?

AnalogyDefinition
Imagine a password prompt: "Enter your password" — again and again, until the user types the correct one. You do not know whether it will take 1, 5, or 50 attempts. The loop simply repeats until the condition is met.

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.

Code examples: Counter and while True

counter = 0
while counter < 5:
    print(f"Iteration {counter}")
    counter += 1
# Output: Iteration 0, 1, 2, 3, 4

counter 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.

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.

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

for loop

Known number of iterations. Iterates over collections or range(). Typical: traversing lists, fixed repetitions.

while loop

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.

Python uses 4 spaces per indentation 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.

Mixing tabs and spaces raises a TabError in Python 3 (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: In later articles, you will encounter nested loops — a loop inside a loop (e.g., rows times columns in a grid). This concept becomes important when working with two-dimensional data structures.

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?

?

What should your code do?

Key Takeaways

  1. if/elif/else evaluates conditions top-to-bottom and executes exactly one branch — the first one that is True. Order matters.
  2. A for loop walks through every element of a sequence or range(). The number of iterations is determined before the loop starts.
  3. 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.
  4. for = "I know how many times." while = "I don't know how many times, but I know when to stop."
  5. Python uses indentation to define code blocks. Getting the whitespace wrong changes what your program does — or breaks it entirely.

Quiz: Control Structures

Question 1 / 4
Not completed

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
Answer Key: 1) B · 2) B · 3) B · 4) B

Comprehension Check

  • In an if/elif/else chain, if multiple conditions could be True at the same time — are all matching blocks executed, or only one? Why?
  • Why does range(5) produce exactly the numbers 0 through 4? Explain how start and stop values work and how this connects to zero-based indexing.
  • What happens in a while loop if you never change the variable checked in the condition? What role can break play?