Conditionals & loops
September 25, 2026
So far the machine runs straight down the lines.
Real programs need to:
if / elif / else;for and while.This is control flow: bending the instruction pointer instead of always marching down.
They compare two values and produce a boolean:
False
True
True False
A comparison is a Boolean expression: it always evaluates to True or False. Don’t confuse = (assign) with == (compare).
True
True
False
Evaluation order: not, then and, then or. Use parentheses to be explicit and readable.
if statementAn if has a condition and a block that runs only when the condition is 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.
The condition is false in both. Predict each output before the click.
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.
Only the indented lines depend on the condition. Everything at the outer level runs as always:
before
after
before and after, with nothing between them. The if did not stop the program — it only skipped its own block.
An if with nothing indented under it is not “an if that does nothing” — it is a broken if:
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:
still running
Four spaces is the convention. The machine only asks that a block be more indented than its if, and consistent inside itself:
two spaces: works
eight spaces: works too
Mixing two widths inside the same block is what breaks:
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 elifelse runs when the condition is False:
this will
elif adds more contingent tests, checked in order until one is True:
pass
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.
Exactly one of the three blocks runs. Swap the two tests around and score = 95 would print pass: order is part of the meaning.
ifAn if block can contain another if. Indentation shows the nesting:
wow
wow a third time
Try moving the last line in or out of the inner block and predict the change before running.
for loopThe last exercise of Lecture 3 ended like this — three near-identical lines:
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.
Carlo Bianchi, age 32
Sara Rossi, age 21
Arianna Verdi, age 21
forNothing 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.
1
2
3
A for is not a formula: it is a sequence of assignments, one per item, each followed by the block.
| 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.
Two consequences people trip on. Predict both before the click.
[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.
Anything the machine can walk through, one item at a time:
a b c
10 20
0 1 2
A dictionary works too — and hands you the keys:
cats
dogs
Need the values as well? .items() from Lecture 3: for key, value in d.items():
A for loop runs its block once per item in a sequence:
1
2
3
4
5
Strings are sequences too:
H
e
l
l
o
rangerange(start, stop) generates numbers from start up to but not including stop:
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.
1 2 3 4 5
range(n) starts at 0; range(a, b, step) lets you skip:
[0, 1, 2]
[0, 2, 4, 6, 8]
A very common pattern: keep a running variable and update it each iteration.
49995000
Building a string works the same way:
anti-missile
anti-anti-missile
anti-anti-anti-missile
foranti-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 tooWe 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?”:
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.
while loop1
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.
while goes wrongTake the count += 1 away — or move it the wrong way — and the condition is never False again:
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:
done
Where you update the counter changes the output:
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.
1
2
3
input()So far every value was written by us, in the code. input() asks the person running the program instead:
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(): validationThe natural partner of input() is while: keep asking until the answer is acceptable.
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 — exit the loop immediately.continue — skip the rest of this iteration, go to the next.starts with 3 consonants
continue in actionhas 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.
Two loops. Say how many numbers each one prints, and which, before the click.
0 3 6 9
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.
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.
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].
-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.
For the string "Appalachicola":
"l" characters it contains."a" characters (case-insensitive).Use += for your counters.
Appalachicola Appalachicola
Appalachicola Appalachicola
Appalachicola Appalachicola
Appalachicola Appalachicola
Appalachicola Appalachicola
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.
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.
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.
Here is the same logic with the typing replaced by a list of pretend answers, so it can run anywhere — the while is identical:
Reusing the list of people from Lecture 3, loop through it and print only the people whose age equals 21.
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.
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?
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.
Given the dictionary
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.
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.
*
**
***
****
*****
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.
Intro to Programming (Python) · Fall 2026