Code Safari

Chapter 143·Beginner·9 min read

Control Flow: Conditionals and Loops

How Python programs make decisions and repeat work — if/elif/else conditionals, comparison and boolean logic, for and while loops, and the range, break, and continue tools that steer them. The leap from a straight-line script to a real program.

July 27, 2026

Everything you've written so far runs the same way every single time: line one, line two, line three, done. Useful, but rigid. Real programs react — they behave differently for an adult than a child, they process a hundred items without you writing a hundred lines. That power comes from control flow: the ability to choose which code runs (conditionals) and to run code repeatedly (loops). Building on the variables and types from last chapter — especially the humble boolean — this is the chapter where your programs come alive.

Making decisions: if, elif, else

The most fundamental decision-maker is the if statement. It runs a block of code only if a condition is true:

temperature = 32
 
if temperature > 30:
    print("It's hot — stay hydrated")

The condition is temperature > 30. If it's true, the indented block runs; if not, Python skips it entirely. Notice the two pieces of grammar: the colon : ends the if line, and the indentation marks what belongs to it — exactly the indentation rule from chapter one, now doing real work.

Often you want alternatives. else catches the case where the if was false, and elif ("else if") checks additional conditions in between:

score = 74
 
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

Python checks each condition in order and runs the block for the first one that's true — then skips the rest entirely. With score = 74, it fails >= 90 and >= 80, matches >= 70, prints Grade: C, and never even looks at else. This top-to-bottom, first-match-wins behaviour is worth internalising.

score >= 90?
else score >= 80?
else score >= 70?
else → F
An if / elif / else chain checks conditions in order, runs the first match

Conditions are boolean expressions

An if needs something that is True or False. Those come from comparison operators, which ask a question and produce a boolean:

OperatorAsksExample (x = 5)
==equal to?x == 5True
!=not equal to?x != 3True
> <greater / less than?x > 10False
>= <=greater/less or equal?x >= 5True

A crucial beginner trap lives here: = assigns, == compares. One equals sign stores a value; two equals signs ask "are these equal?" Mixing them up is one of the most common early mistakes.

You combine conditions with the words and, or, and not — Python spells these out in English rather than using symbols:

age = 20
has_ticket = True
 
if age >= 18 and has_ticket:
    print("Welcome in")
 
if not has_ticket:
    print("Please buy a ticket")

and is true only when both sides are; or is true when either is; not flips true and false. With comparisons and these three words, you can express essentially any condition you'll ever need.

Repeating with for loops

The second superpower is repetition. A for loop runs its body once for each item in a sequence — no matter how many there are:

for name in ["Ada", "Alan", "Grace"]:
    print(f"Hello, {name}")

This prints three greetings. The variable name takes each value in turn — "Ada", then "Alan", then "Grace" — and the indented body runs each time. Write the loop once; it scales to a list of three or three million.

To repeat a set number of times, pair for with range(), which generates a sequence of numbers:

for i in range(5):
    print(i)        # prints 0, 1, 2, 3, 4

Note two Python habits: range(5) counts from 0 and stops before 5, giving 0,1,2,3,4 — five numbers. Starting at zero and excluding the endpoint feels odd at first but becomes natural fast, and it matches how Python numbers things elsewhere. You can loop over the characters of a string, too, since a string is just a sequence of characters — a theme we'll expand into full collections next chapter.

Repeating with while loops

A while loop takes a different angle: it repeats as long as a condition stays true, rechecking before each pass. Use it when you don't know the number of repetitions in advance:

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Lift off!")

This prints 3, 2, 1, then Lift off!. Before each pass Python checks count > 0; the body counts count down; eventually it hits 0, the condition is false, and the loop ends.

Steering loops: break and continue

Two keywords give you finer control inside any loop. break exits the loop immediately, and continue skips to the next iteration:

for n in range(1, 10):
    if n == 5:
        break          # stop the whole loop at 5
    if n % 2 == 0:
        continue       # skip even numbers
    print(n)           # prints 1, 3

break is perfect for "stop as soon as I find what I'm looking for"; continue for "skip the ones I don't care about." (% there is the modulo operator — the remainder after division — so n % 2 == 0 is the idiomatic test for "even.")

Where this leaves us

You've unlocked the two ideas that separate a real program from a fixed script: conditionals (if/elif/else, driven by boolean comparisons and and/or/not) to make decisions, and loops (for over sequences, while on a condition, steered by break and continue) to repeat work. Combine them — a loop with an if inside — and you can express a startling range of behaviour.

Our loops have been walking over little lists of items in passing. It's time to make those collections first-class. Next we meet Python's built-in containers for holding many values at once — lists, tuples, dictionaries, and sets — and the operations that make them so powerful: Collections.

Control Flow: Conditionals and Loops | Code Safari