Control Flow

Conditionals & loops

Paolo Rota

September 25, 2026

Where we are

So far the machine runs straight down the lines.
Real programs need to:

  • choose between paths → if / elif / else;
  • repeat work → for and while.

This is control flow: bending the instruction pointer instead of always marching down.

Comparisons

Comparison operators

They compare two values and produce a boolean:

<     less than            a < b
>     greater than         a > b
<=    less than or equal   a <= b
>=    greater than or equal a >= b
==    equal to             a == b
!=    not equal to         a != b
a, b = 5, 7
print(a > b)
print(a < b)
print(a != b, a == b)
False
True
True False

A comparison is a Boolean expression: it always evaluates to True or False. Don’t confuse = (assign) with == (compare).

Combining conditions

x = 5
print(x > 3 and x < 10)     # both must hold
print(x < 0 or x > 3)       # at least one holds
print(not (x == 5))
True
True
False

Evaluation order: not, then and, then or. Use parentheses to be explicit and readable.

The if statement

Grouping & indentation

An if has a condition and a block that runs only when the condition is True.

if 2 + 2 == 4:
    print("that was true")
    print("...really true")
that was true
...really true

Python uses indentation (conventionally 4 spaces) to mark a block. The indentation is the scope of the block — it is not decoration.

In, or out?

The condition is false in both. Predict each output before the click.

if 2 + 2 == 5:
    print("A")
    print("B")
print("done")
done
if 2 + 2 == 5:
    print("A")
print("B")
print("done")
B
done

Left prints only done: both lines are inside the block, and the block is skipped. Right prints B and then done: four spaces fewer, and that line is no longer part of the if — it runs whatever the condition says.

The done is there so you can see that both programs really did run.

Around the block

Only the indented lines depend on the condition. Everything at the outer level runs as always:

print("before")
if 2 + 2 == 5:
    print("inside")
print("after")
before
after

before and after, with nothing between them. The if did not stop the program — it only skipped its own block.

What if the block is empty?

An if with nothing indented under it is not “an if that does nothing” — it is a broken if:

if 2 + 2 == 4:
print("this line is not indented")
  Cell In[7], line 2
    print("this line is not indented")
    ^
IndentationError: expected an indented block after 'if' statement on line 1

Python insists on a block. When you genuinely want one that does nothing, say so out loud with pass:

if 2 + 2 == 4:
    pass          # "on purpose, do nothing here"

print("still running")
still running

How much indentation?

Four spaces is the convention. The machine only asks that a block be more indented than its if, and consistent inside itself:

if 2 + 2 == 4:
  print("two spaces: works")

if 2 + 2 == 4:
        print("eight spaces: works too")
two spaces: works
eight spaces: works too

Mixing two widths inside the same block is what breaks:

if 2 + 2 == 4:
    print("four here")
        print("eight there")
  Cell In[10], line 3
    print("eight there")
    ^
IndentationError: unexpected indent

Use four spaces and let your editor do it. The freedom above is worth knowing only so that the two error messages make sense when you meet them:

  • expected an indented block — you opened an if and gave it nothing.
  • unexpected indent — you indented a line that had no reason to be.

The machine reads indentation to know which statements belong to the if; get it wrong and it stops before running anything.

else and elif

else runs when the condition is False:

if 2 + 2 == 5:
    print("won't print")
else:
    print("this will")
this will

elif adds more contingent tests, checked in order until one is True:

score = 75
if score >= 90:
    print("A")
elif score >= 60:
    print("pass")
else:
    print("fail")
pass

One path is taken, then the code rejoins

elif tests are checked in order and the machine stops at the first True. Everything after it is skipped — then all paths meet again below.

score >= 90 ? score >= 60 ? everything else the next line True False True False

Exactly one of the three blocks runs. Swap the two tests around and score = 95 would print pass: order is part of the meaning.

Nested if

An if block can contain another if. Indentation shows the nesting:

if 2 + 2 == 4:
    print("wow")
    if 7 * 7 == 48:
        print("wow again")     # skipped: 7*7 is 49
    print("wow a third time")
wow
wow a third time

Try moving the last line in or out of the inner block and predict the change before running.

The for loop

Why loops

The last exercise of Lecture 3 ended like this — three near-identical lines:

print(f"{p1['name']} {p1['surname']}, age {p1['age']}")
print(f"{p2['name']} {p2['surname']}, age {p2['age']}")
print(f"{p3['name']} {p3['surname']}, age {p3['age']}")

Three people, three lines. Three hundred people, three hundred lines — and a new line every time the list changes.

Repetition in your code is a smell. A loop writes the instruction once and lets the machine repeat it, however many items there are.

people = [
    {"name": "Carlo",   "surname": "Bianchi", "age": 32},
    {"name": "Sara",    "surname": "Rossi",   "age": 21},
    {"name": "Arianna", "surname": "Verdi",   "age": 21},
]

for person in people:
    print(f"{person['name']} {person['surname']}, age {person['age']}")
Carlo Bianchi, age 32
Sara Rossi, age 21
Arianna Verdi, age 21

Anatomy of a for

for number in numbers: print(number) number — a name YOU choose. The machine refills it each round. numbers — must already exist: a list, a string, a range… the indented block — what to do, once per item.

Nothing about the name number is special — it does not have to be the singular of numbers. You pick it, and the machine puts each item into it in turn.

numbers = [1, 2, 3]

for banana in numbers:      # any name works
    print(banana)
1
2
3

What the machine actually does

A for is not a formula: it is a sequence of assignments, one per item, each followed by the block.

What you write

for number in numbers:
    print(number)

What happens, step by step

number = numbers[0]
print(number)
number = numbers[1]
print(number)
number = numbers[2]
print(number)
Round number Screen so far
1 1 1
2 2 1 2
3 3 1 2 3

The same box, refilled every round — Rule 3 from Lecture 2 inside a loop. If you can trace x = 5, you can trace a for.

The name is just a box

Two consequences people trip on. Predict both before the click.

nums = [10, 20, 30]

for n in nums:
    n = n * 100      # change the box...

print(nums)          # ...did the list change?
print(n)             # ...and does n still exist out here?
[10, 20, 30]
3000

The list is untouched: n is a box of its own, and at the next round the machine refills it from the list, throwing your n * 100 away. And n does survive the loop, holding the last value it was given — 3000, because the last round did run the multiplication.

What can go on the right?

Anything the machine can walk through, one item at a time:

for ch in "abc":            # a string: one character at a time
    print(ch, end=" ")
print()

for x in (10, 20):          # a tuple
    print(x, end=" ")
print()

for i in range(3):          # a range
    print(i, end=" ")
a b c 
10 20 
0 1 2 

A dictionary works too — and hands you the keys:

for key in {"cats": 7, "dogs": 3}:
    print(key)
cats
dogs

Need the values as well? .items() from Lecture 3: for key, value in d.items():

Iterating over a sequence

A for loop runs its block once per item in a sequence:

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)
1
2
3
4
5

Strings are sequences too:

for char in "Hello":
    print(char)
H
e
l
l
o

Counting with range

range(start, stop) generates numbers from start up to but not including stop:

0 1 2 3 4 5 6 start — included stop — left out range(1, 6)

Same rule as slicing in Lecture 3: s[1:4] stopped before position 4, and range(1, 6) stops before 6. In both cases stop - start tells you how many you get — here 6 - 1 = 5 numbers.

for i in range(1, 6):
    print(i, end=" ")
1 2 3 4 5 

More ways to count

range(n) starts at 0; range(a, b, step) lets you skip:

print(list(range(3)))
print(list(range(0, 10, 2)))
[0, 1, 2]
[0, 2, 4, 6, 8]

Accumulating in a loop

A very common pattern: keep a running variable and update it each iteration.

total = 0
for i in range(10000):
    total = total + i     # or: total += i
print(total)
49995000

Building a string works the same way:

prefix = "anti"
word = "missile"
for i in range(3):
    word = prefix + "-" + word
    print(word)
anti-missile
anti-anti-missile
anti-anti-anti-missile

Nested for

words = ["missile", "racism", "music"]
for word in words:            # outer: each word
    for i in range(2):        # inner: twice per word
        word = "anti-" + word
        print(word)
anti-missile
anti-anti-missile
anti-racism
anti-anti-racism
anti-music
anti-anti-music

The inner loop runs completely for every step of the outer loop.

in asks a question too

We used in to drive a for loop. The same word also works as a test, and then it evaluates to a boolean — in a string it asks “does this appear inside?”:

print("a" in "banana")
print("z" in "banana")
print("nan" in "banana")   # a whole piece of text, not just one character
True
False
True

Two different jobs, one word. for ch in word: walks through the items; if ch in vowels: asks whether an item is there. The for gives it the first meaning, an if the second.

The while loop

Repeat while a condition holds

count = 0
while count < 3:
    count += 1        # the "escape clause" — moves toward stopping
    print(count)
1
2
3

A for walks a collection that has a last item, so it always ends.

Careful — what can go wrong here that could never go wrong with a for? Nobody counts the rounds for you. The block itself has to move the condition towards False, and nothing forces you to write that line.

When while goes wrong

Take the count += 1 away — or move it the wrong way — and the condition is never False again:

count = 1
while count > 0:      # count only grows: never False
    count += 1
    print(count)

This is an infinite loop. It is the one block on these slides that is not executed: a cell that never ends would hang the whole deck. Run it yourself and stop it with Ctrl+C in the terminal, or the ■ button in a notebook.

The opposite failure is quieter — a condition already False at the start runs the block zero times, with no error at all:

count = 10
while count < 3:
    print("never printed")

print("done")
done

Order matters

Where you update the counter changes the output:

count = 0
while count < 3:
    print(count)      # printed BEFORE the increment
    count += 1
0
1
2

Compare with the previous slide, where count += 1 came first: same three rounds, different numbers on screen. Trace the condition each time round to predict behaviour.

count = 0
while count < 3:
    count += 1
    print(count)      # printed AFTER the increment
1
2
3

Talking to the user

input()

So far every value was written by us, in the code. input() asks the person running the program instead:

name = input("What is your name? ")
print(f"Hello, {name}!")

The machine stops at that line and waits until the user presses Enter, then input() hands back what they typed.

Whatever they type comes back as a string, always — even 42. To do arithmetic with it, convert first: int(input(...)). Forgetting this is the classic beginner bug: "5" + 1 is the TypeError from Lecture 3.

These two cells cannot run on a slide — there is nobody to type — but they run in your terminal. Everything else today does.

while + input(): validation

The natural partner of input() is while: keep asking until the answer is acceptable.

n = int(input("A number between 5 and 10: "))

while n < 5 or n > 10:
    print("Not in range, try again.")
    n = int(input("A number between 5 and 10: "))

print("Thanks!")

Read the condition as “while the answer is still wrong, ask again”. The first input() before the loop is what gives n a value for the very first test — without it, the while would look at a box that does not exist.

break & continue

Escaping and skipping

  • break — exit the loop immediately.
  • continue — skip the rest of this iteration, go to the next.
vowels = "aeiou"
word = "sthenic"
counter = 0
for ch in word:
    if ch in vowels:
        break          # stop at the first vowel
    counter += 1
print("starts with", counter, "consonants")
starts with 3 consonants

continue in action

vowels = "aeiou"
word = "sthenic"
counter = 0
for ch in word:
    if ch in vowels:
        continue       # skip vowels
    counter += 1       # count only consonants
print("has", counter, "consonant letters")
has 5 consonant letters

for when you know the items to visit; while when you loop until a condition changes. Anything a for does, a while can too — but usually less clearly.

Try it now

How many lines?

Two loops. Say how many numbers each one prints, and which, before the click.

for i in range(0, 10, 3):
    print(i, end=" ")
0 3 6 9 
for i in range(10, 0, -3):
    print(i, end=" ")
10 7 4 1 

Four each. 0 3 6 9 — the step jumps by 3 and 10 is the stop, never reached. Then 10 7 4 1 — a negative step counts down, and again it stops before 0.

break or continue?

The same loop twice, one word changed. Predict both outputs.

for ch in "python":
    if ch == "h":
        break
    print(ch, end=" ")
p y t 
for ch in "python":
    if ch == "h":
        continue
    print(ch, end=" ")
p y t o n 

p y t — break leaves the loop at the h, so o and n are never looked at. p y t o n — continue skips only that one round and carries on, so everything except the h is printed.

Exercises

Exercise 1 — Classify a number

Given a number n, print:

  • "negative" if n < 0,
  • "zero" if n == 0,
  • "small" if 0 < n <= 10,
  • "large" otherwise.

Use if / elif / else. Test all four values with a for loop over the list [-4, 0, 7, 250].

for n in [-4, 0, 7, 250]:
    if n < 0:
        print(n, "negative")
    elif n == 0:
        print(n, "zero")
    elif n <= 10:          # we already know n > 0 here
        print(n, "small")
    else:
        print(n, "large")
-4 negative
0 zero
7 small
250 large

The third test does not need 0 < n : if the machine got that far, the two tests above were both False, so n is already known to be positive.

Exercise 2 — Count letters & vowels

For the string "Appalachicola":

  1. Print it 10 times; end odd iterations with a space and even ones with a newline.
  2. Count how many "l" characters it contains.
  3. Count how many "a" characters (case-insensitive).
  4. Count the total number of vowels.

Use += for your counters.

word = "Appalachicola"

for i in range(1, 11):
    if i % 2 == 1:          # odd iteration
        print(word, end=" ")
    else:
        print(word)         # even: print's own newline ends the line
Appalachicola Appalachicola
Appalachicola Appalachicola
Appalachicola Appalachicola
Appalachicola Appalachicola
Appalachicola Appalachicola
ls = 0
a_count = 0
vowels = 0

for ch in word:
    if ch == "l":
        ls += 1
    if ch.lower() == "a":            # lower() makes the test case-insensitive
        a_count += 1
    if ch.lower() in "aeiou":
        vowels += 1

print("l:", ls, " a:", a_count, " vowels:", vowels)
l: 2  a: 4  vowels: 6

Three separate ifs: a character can be an a and a vowel, so every test must be asked, and elif would stop at the first true one.

Exercise 3 — Letter combinations

Given two strings, e.g. "AB" and "XY", print all two-letter combinations taking the first letter from the first string and the second from the second:

AX AY BX BY

Hint: a nested for loop.

for first in "AB":
    for second in "XY":
        print(first + second)
AX
AY
BX
BY

The inner loop runs completely for each step of the outer one: that is why the second letter changes fastest.

Exercise 4 — Validate input in a loop

Write a loop that keeps asking for a number with input() until the user enters one between 5 and 10 (inclusive). When they finally do, print "Thanks!". Run this one in your terminal.

n = int(input("A number between 5 and 10: "))

while n < 5 or n > 10:
    print("Not in range, try again.")
    n = int(input("A number between 5 and 10: "))

print("Thanks!")

Here is the same logic with the typing replaced by a list of pretend answers, so it can run anywhere — the while is identical:

answers = ["3", "12", "7"]     # what the user "types", in order
i = 0

n = int(answers[i])
while n < 5 or n > 10:
    print("Not in range, try again.")
    i += 1
    n = int(answers[i])

print("Thanks!")
Not in range, try again.
Not in range, try again.
Thanks!

Exercise 5 — Filter a list

Reusing the list of people from Lecture 3, loop through it and print only the people whose age equals 21.

people = [
    {"name": "Carlo",   "surname": "Bianchi", "age": 32},
    {"name": "Sara",    "surname": "Rossi",   "age": 21},
    {"name": "Arianna", "surname": "Verdi",   "age": 21},
]

for person in people:
    if person["age"] == 21:
        print(person["name"], person["surname"])
Sara Rossi
Arianna Verdi

A loop that walks every item and an if that keeps only some: the two halves of today’s lecture in four lines.

Exercise 6 — The first long word

Given words = ["cat", "dog", "hippo", "ox", "giraffe"], print the first word longer than four letters — and stop looking as soon as you find it.

Which of break and continue do you need?

words = ["cat", "dog", "hippo", "ox", "giraffe"]

for w in words:
    if len(w) > 4:
        print("first long word:", w)
        break            # found it — no reason to look at the rest
first long word: hippo

Without the break you would also print giraffe: the loop would keep walking. continue would be the wrong tool — it skips a round, it does not stop.

Exercise 7 — Frequent words

Given the dictionary

counts = {"the": 12, "cat": 3, "sat": 1, "on": 7}

print only the words that appear more than 5 times, with their count.

Remember from earlier today: looping over a dictionary gives you its keys.

counts = {"the": 12, "cat": 3, "sat": 1, "on": 7}

for word in counts:              # word takes each KEY in turn
    if counts[word] > 5:
        print(word, counts[word])
the 12
on 7

counts[word] is how you get from the key to its value — the same square brackets as in Lecture 3.

Exercise 8 — A triangle

Print this, using range:

* ** *** **** *****

Then do it a second way: one loop for the rows and another inside it for the stars in that row.

for i in range(1, 6):
    print("*" * i)           # a string times a number, from Lecture 2
*
**
***
****
*****
for i in range(1, 6):
    for star in range(i):    # the inner range depends on the outer i
        print("*", end="")
    print()                  # end this row
*
**
***
****
*****

The second version is the interesting one: the inner loop runs i times, so it does more work on every row. Same output, and the first version is the one to prefer — shorter and easier to read.

Questions?