4. Choices and repetition with if, while and for
Until now, your program executed every line, always in the same order. Real work calls for choices: a course is full or not, an item has to be ordered or not, a customer gets a discount or not. And it calls for repetition: the same check for every line of a list, a hundred times in a row, without writing a hundred lines of code. That is what control statements are for. With these few words you can probably already write out most of the task from the introduction.
After this chapter:
- You write comparisons that return True or False, and you combine them with
and,orennot. - If you run your program with
if,elifenelseprecies één pad kiezen. - You repeat with
whilezolang een voorwaarde klopt. - If you loop with
fordoor een lijst, filter je metifen stop je metbreak. - If you repeat a fixed number of times with
range().
Comparisons that return True or False
A comparison has only two possible answers: True of False. Die twee waarden vormen een eigen type, bool. Je vergelijkt met == (gelijk aan, met twee istekens: met één isteken geef je juist een waarde), != (niet gelijk aan), < en > (kleiner en groter dan) en <= en >= (kleiner of gelijk, groter of gelijk). Met and, or en not combineer je vergelijkingen. Bij and moeten beide kanten waar zijn, bij or is één kant genoeg, en not draait het antwoord om. Ook in uit hoofdstuk 3 geeft True of False.
vergelijken.py
prijs = 395.50
deelnemers = 12
print(prijs > 400)
print(deelnemers >= 12)
print(prijs > 400 and deelnemers >= 12)
print(prijs > 400 or deelnemers >= 12)
print(not prijs > 400)
rooster = ["Python basis", "SQL basis", "Excel gevorderd"]
print("SQL basis" in rooster)
print("Java basis" in rooster)
Output
False
True
False
True
True
True
False
If you doubt whether a comparison does what you think, you put print() omheen of typ je hem in de interactieve prompt. Daar zie je meteen True of False, zonder dat je je hele script hoeft te draaien.
Making choices with if, elif and else
After if zet je een vergelijking, daarna een dubbele punt. De ingesprongen regels eronder draaien alleen als die vergelijking True is. Met elif (een samentrekking van else en if) voeg je een volgende vraag toe, en met else vang je alle overige gevallen op. Python loopt de vragen van boven naar beneden af en stopt bij de eerste die klopt. Je mag zoveel elif-takken gebruiken als je wilt; else is er hooguit één en staat onderaan.
keuze.py
inschrijvingen = 9
max_deelnemers = 12
if inschrijvingen >= max_deelnemers:
print("Vol: nieuwe aanmeldingen op de wachtlijst")
elif inschrijvingen >= max_deelnemers - 3:
print("Bijna vol: nog", max_deelnemers - inschrijvingen, "plekken")
else:
print("Er is nog ruim plek")
Output
Bijna vol: nog 3 plekken
9 is not 12 or more, so the first question gives False. 9 is 9 or more (12 minus 3), so the second branch runs, and the else wordt overgeslagen.
Pieter sells software licences at 120 euros each. From 10 licences the customer gets a 10 per cent discount, from 50 licences 20 per cent. He writes a calculation tool for the sales support team:
staffel.py
aantal = int(input("Aantal licenties: "))
stukprijs = 120
if aantal >= 50:
korting = 0.20
elif aantal >= 10:
korting = 0.10
else:
korting = 0
totaal = aantal * stukprijs * (1 - korting)
print(f"Korting: {korting:.0%}")
print(f"Totaal: {totaal:.2f} euro")
In the terminal
Aantal licenties: 25
Korting: 10%
Totaal: 2700.00 euro
25 licences is not 50 or more, but it is 10 or more: 10 per cent discount. 25 times 120 is 3000, minus 10 per cent is 2700. In the f-string, put :.0% het getal 0.10 om in een percentage zonder decimalen.
Then a colleague puts the conditions in a different order, because 10 comes before 50:
staffel.py
aantal = int(input("Aantal licenties: "))
stukprijs = 120
if aantal >= 10:
korting = 0.10
elif aantal >= 50:
korting = 0.20
else:
korting = 0
totaal = aantal * stukprijs * (1 - korting)
print(f"Korting: {korting:.0%}")
print(f"Totaal: {totaal:.2f} euro")
In the terminal
Aantal licenties: 60
Korting: 10%
Totaal: 6480.00 euro
A customer with 60 licences now gets only 10 per cent. The first question, is 60 10 or more, already returns True, and then Python stops asking. The branch for 50 and more is never reached. With a sliding scale, you therefore always put the strictest condition first.

The diagram shows why the order matters. Python first asks whether the quantity is 50 or more. If yes, the discount is 20 per cent and that is the end of it. If no, the next question is whether it is 10 or more: if yes, 10 per cent; if no, it goes into the else en is de korting 0. Welke route ook, alle drie komen ze uit bij het berekenen van het totaal.
A forgotten colon is at if de klassieke fout. Python wijst de plek precies aan:
keuze.py
inschrijvingen = 14
max_deelnemers = 12
if inschrijvingen > max_deelnemers
print("Wachtlijst")
else:
print("Er is nog plek")
Output
File "/tmp/cursus/keuze.py", line 4
if inschrijvingen > max_deelnemers
^
SyntaxError: expected ':'
Repeating with while
A while-lus herhaalt een blok zolang een vergelijking True oplevert. Voor elke ronde kijkt Python opnieuw naar de voorwaarde. Zodra die False is, gaat hij verder met de eerste regel onder het blok. Bij het cursusrooster werk je zo een wachtlijst af zolang er plekken vrij zijn:
wachtlijst.py
wachtlijst = ["Sanne", "Idris", "Fatima", "Tom"]
plekken = 2
positie = 0
while positie < plekken:
print(f"{wachtlijst[positie]} krijgt een plek")
positie = positie + 1
print(f"Nog op de wachtlijst: {len(wachtlijst) - positie}")
Output
Sanne krijgt een plek
Idris krijgt een plek
Nog op de wachtlijst: 2
The line positie = positie + 1 is hier de belangrijkste: die zorgt dat de voorwaarde ooit False wordt. Na twee rondes is positie 2, en 2 is niet kleiner dan 2.
If you forget to increment the counter, the condition always remains true and your program keeps running until you stop it. Ctrl+C stops a stuck script in the terminal.
while is vooral handig als je niet van tevoren weet hoe vaak je moet herhalen, zoals bij invoer: je blijft vragen tot de gebruiker klaar is.
invoer.py
antwoord = ""
while antwoord != "stop":
antwoord = input("Cursusnaam (of stop): ").strip().lower()
if antwoord != "stop":
print(f"Genoteerd: {antwoord}")
print("Klaar met invoeren")
In the terminal
Cursusnaam (of stop): Python basis
Genoteerd: python basis
Cursusnaam (of stop): SQL Basis
Genoteerd: sql basis
Cursusnaam (of stop): stop
Klaar met invoeren
The second input had spaces and capital letters, but strip() en lower() uit hoofdstuk 2 maken er een nette naam van. Omdat antwoord bij de start een lege tekst is, klopt de voorwaarde de eerste keer altijd.
Looping through a list with for
If you already know the set, then for de logische keuze. Achter for zet je een naam, dan in en de lijst. Per ronde krijgt die naam de volgende waarde uit de lijst, en als de lijst op is, stopt de lus vanzelf. Een teller bijhouden zoals bij while hoeft niet. Interessant wordt het als je for en if combineert. Hier komt de "1 dagen" uit hoofdstuk 3 terug: met een if in de lus maak je er "1 dag" van.
rooster.py
rooster = [
{"naam": "Python basis", "dagen": 3, "prijs": 1495.00},
{"naam": "SQL basis", "dagen": 2, "prijs": 995.00},
{"naam": "Excel gevorderd", "dagen": 1, "prijs": 525.00},
]
for cursus in rooster:
if cursus["dagen"] == 1:
duur = "1 dag"
else:
duur = f"{cursus['dagen']} dagen"
print(f"{cursus['naam']:<16} {duur:<8} EUR {cursus['prijs']:>8.2f}")
Output
Python basis 3 dagen EUR 1495.00
SQL basis 2 dagen EUR 995.00
Excel gevorderd 1 dag EUR 525.00
Thijs manages the office supplies. Every Friday he goes through the cupboard with a list: what has run out, what is running low, what is sufficient. That list is now a list of dictionaries, and going through it is done by a for loop with three branches:
voorraad.py
voorraad = [
{"artikel": "Toner zwart", "op_voorraad": 3, "minimum": 5},
{"artikel": "Papier A4", "op_voorraad": 40, "minimum": 20},
{"artikel": "Nietjes", "op_voorraad": 0, "minimum": 2},
{"artikel": "Whiteboardstift", "op_voorraad": 12, "minimum": 10},
]
te_bestellen = 0
for regel in voorraad:
tekort = regel["minimum"] - regel["op_voorraad"]
if regel["op_voorraad"] == 0:
print(f"OP: {regel['artikel']} (bestel {regel['minimum']})")
te_bestellen = te_bestellen + 1
elif tekort > 0:
print(f"BIJNA: {regel['artikel']} (bestel {tekort})")
te_bestellen = te_bestellen + 1
else:
print(f"GENOEG: {regel['artikel']}")
print(f"Artikelen om te bestellen: {te_bestellen}")
Output
BIJNA: Toner zwart (bestel 2)
GENOEG: Papier A4
OP: Nietjes (bestel 2)
GENOEG: Whiteboardstift
Artikelen om te bestellen: 2
The order of the branches matters again. Nietjes (staples) have a stock of 0 and a minimum of 2, so the shortfall is also 2 and tekort > 0 zou kloppen. Maar de vraag of de voorraad 0 is, staat erboven, dus komt het artikel in de tak OP terecht. Toner zwart heeft 3 op voorraad bij een minimum van 5: niet op, wel een tekort van 2. Papier en whiteboardstiften zitten op of boven het minimum. De teller te_bestellen loopt alleen op in de twee takken waar iets besteld moet worden, en de laatste regel staat buiten de lus, dus hij draait één keer, aan het eind.
If you are looking for just one thing, you leave the loop immediately with break. Het rooster zoekt nu een cursus op die de gebruiker intypt, ongeacht hoofdletters. Een tweede variabele, gevonden, onthoudt of het gelukt is:
zoeken.py
rooster = [
{"naam": "Python basis", "dagen": 3, "prijs": 1495.00},
{"naam": "SQL basis", "dagen": 2, "prijs": 995.00},
{"naam": "Excel gevorderd", "dagen": 1, "prijs": 525.00},
]
gezocht = input("Welke cursus zoek je? ").strip().lower()
gevonden = False
for cursus in rooster:
if cursus["naam"].lower() == gezocht:
print(f"{cursus['naam']}: {cursus['dagen']} dagen, {cursus['prijs']:.2f} euro")
gevonden = True
break
if not gevonden:
print("Die cursus staat niet in het rooster")
In the terminal
Welke cursus zoek je? sql BASIS
SQL basis: 2 dagen, 995.00 euro
If someone types a course that is not in the list, the loop runs all the way through without finding anything, and the line at the end reports that:
In the terminal
Welke cursus zoek je? Java basis
Die cursus staat niet in het rooster
With that, the schedule does what the introduction promised: someone on the phone asks about a course, and the program gives the duration and the price, or honestly says that it does not exist.
This code should display the three courses with their prices and, at the end, the total for the whole schedule, once. But the output is wrong:
totaal.py
rooster = [
{"naam": "Python basis", "dagen": 3, "prijs": 1495.00},
{"naam": "SQL basis", "dagen": 2, "prijs": 995.00},
{"naam": "Excel gevorderd", "dagen": 1, "prijs": 525.00},
]
totaal = 0
for cursus in rooster:
print(f"{cursus['naam']}: {cursus['prijs']:.2f}")
totaal = totaal + cursus["prijs"]
print(f"Totaal: {totaal:.2f}")
Output
Python basis: 1495.00
Totaal: 1495.00
SQL basis: 995.00
Totaal: 2490.00
Excel gevorderd: 525.00
Totaal: 3015.00
The total appears three times in the output, after each course. Which line is in the wrong place, and how do you fix it so that only "Totaal: 3015.00" appears at the bottom?
The last one print() staat ingesprongen en hoort dus bij de lus: hij draait in elke ronde. Haal je de vier spaties ervoor weg, dan staat hij na de lus en draait hij één keer.
A fixed number of times with range()
Sometimes you do not want to loop through an existing list, but simply repeat something a number of times. For that, range(). Die maakt een reeks hele getallen. Je geeft één, twee of drie getallen mee: alleen een stopwaarde, een start en een stop, of daarnaast een stapgrootte. Met list() eromheen zie je welke getallen het zijn.
range.py
print(list(range(5)))
print(list(range(1, 10)))
print(list(range(0, 21, 5)))
for dag in range(1, 4):
print(f"Dag {dag} van de cursus")
Output
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 5, 10, 15, 20]
Dag 1 van de cursus
Dag 2 van de cursus
Dag 3 van de cursus
As with slicing, the stop value is not included: range(1, 10) eindigt bij 9, en range(5) geeft vijf getallen, van 0 tot en met 4. Wil je de dagen 1, 2 en 3 van een cursus, dan schrijf je dus range(1, 4).
Choices and loops at a glance
- A comparison returns True or False.
==vergelijkt,=geeft een waarde. if,elif,else: Python stopt bij de eerste tak die klopt. Bij een staffel staat de strengste voorwaarde bovenaan.whileherhaalt zolang de voorwaarde klopt. In het blok moet iets veranderen dat de voorwaarde ooit False maakt.forloopt door een lijst en stopt vanzelf aan het eind. Metbreakstop je eerder.- Whatever is indented runs in every round; whatever comes after it, flush left, runs once.
range(start, stop, stap)geeft hele getallen; de stopwaarde doet niet mee.
The scale starts with if aantal >= 10: en daarna elif aantal >= 50:. Wat krijgt een klant met 60 licenties?
Which numbers gives range(1, 4)?
A while-lus stopt niet meer en het script blijft draaien. Wat is de meest waarschijnlijke oorzaak?
Ready for the next step?
You have completed the free starter of Python programming basics. The next chapter in the full course is Tuples and sets: Values fixed in a tuple, unpacking them into separate names, and counting and comparing unique values with a set.
Take the 3-day course →From €1875,- excl. VAT · with an experienced trainer