Back to Learning Area

Control Structures

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

  • Fundamentals
  • 12 min
  • Beginner

Plain Language

This preview is in Plain Language. The whole portal is also available in Plain Language. You can change the language at the top. Or use the button below. Our Plain Language texts are AI-assisted and editorially reviewed. They follow the core principles of easy-to-read language, but they are not certified Easy Read: a review panel of people with learning difficulties does not test them.

Preview: How code makes decisions

What are control structures?

A program runs from top to bottom. With control structures, it can make decisions. It can also repeat steps. This makes code much more flexible.

If-then: branches

Code can make decisions. This works with if. If means: what if. The program checks a condition. If it is true, it performs a step. Otherwise, it does something else.

Loops repeat code

Loops repeat code. For-loops go through a list. For means: for every element. While-loops run as long as a condition is true. This way, you only write code once.

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

Imagine a bouncer at a club entrance. They check your age against the club's own house 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

Note

Execution trace: age = 17

  1. 1. Read input: age = 17
  2. 2. Check age >= 18 → False → skip block
  3. 3. Check age >= 16 → True → execute block: "Soft drinks only"
  4. 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

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 over a list or a range() 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.

Note

Code examples: Lists and range()

fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
    print(fruit)
# Output (one value per line): 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 (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

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.

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

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

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.

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

  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(). For lists and range(), the number of iterations is fixed 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.

Check

Quiz: Control Structures

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

Check

Comprehension Check

Can you explain this in your own words? Tick what you've got.

0 of 3 done