Programma’s voeren stappen uit in een bepaalde volgorde. Met controle-structuren stuur je die volgorde: je voert code conditioneel uit, herhaalt ze, of slaat ze over. In deze notebook leer je ook comprehensions en lambda-functies — twee compacte schrijfwijzen die je voortdurend tegenkomt in ML code.
Condities: if / elif / else¶
Met een if-statement voer je een blok code alleen uit als een conditie True is.
score = 74
if score >= 90:
print("Distinction")
elif score >= 60:
print("Passed")
else:
print("Failed")Passed
# Ternary expression — compact if/else on one line
status = "passed" if score >= 60 else "failed"
print(status)passed
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)apple
banana
cherry
# range(start, stop, step)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i, end=" ")
print() # newline0 2 4 6 8
# enumerate() gives index + value simultaneously
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")1. apple
2. banana
3. cherry
# zip() pairs two sequences element by element
names = ["Alice", "Bob", "Charlie"]
scores = [88, 74, 95]
for name, score in zip(names, scores):
print(f"{name}: {score}")Alice: 88
Bob: 74
Charlie: 95
while-lus¶
Een while-lus blijft herhalen zolang een conditie True is. Gebruik dit wanneer je het aantal iteraties op voorhand niet kent.
counter = 1
while counter <= 5:
print(counter)
counter += 11
2
3
4
5
break en continue¶
break: beëindigt de lus onmiddellijkcontinue: slaat de rest van de huidige iteratie over en gaat naar de volgende
# Find the first even number greater than 10
for n in range(11, 30):
if n % 2 == 0:
print(f"First even number > 10: {n}")
breakFirst even number > 10: 12
# Skip odd numbers
for n in range(1, 11):
if n % 2 != 0:
continue
print(n, end=" ")
print()2 4 6 8 10
Comprehensions¶
Comprehensions zijn een compacte en leesbare manier om lijsten, dictionaries of sets te bouwen op basis van een reeks. Ze vervangen een for-lus + append()-patroon door één expressie.
[expression for element in sequence if condition]# List comprehension
squares = [x**2 for x in range(1, 8)]
print(squares)[1, 4, 9, 16, 25, 36, 49]
# Filter and transform in one step
words = ["data", "science", "AI", "ML", "python", "notebook"]
long_words = [w.upper() for w in words if len(w) > 4]
print(long_words)['SCIENCE', 'PYTHON', 'NOTEBOOK']
# Dictionary comprehension
names = ["Alice", "Bob", "Charlie"]
scores = [88, 74, 95]
report = {name: score for name, score in zip(names, scores)}
print(report){'Alice': 88, 'Bob': 74, 'Charlie': 95}
# Set comprehension — automatically unique values
text = "programming is fun and programming is useful"
unique_words = {w for w in text.split()}
print(unique_words){'useful', 'and', 'is', 'fun', 'programming'}
Lambda-functies¶
Een lambda is een anonieme functie die in één expressie geschreven wordt. Gebruik ze voor eenvoudige, éénmalige transformaties — typisch als argument voor sorted(), map() of .apply() in Pandas.
lambda arguments: expression# Simple lambda
double = lambda x: x * 2
print(double(5)) # 1010
# Lambda as sort key
students = [("Alice", 88), ("Bob", 74), ("Charlie", 95), ("Diana", 81)]
# Sort by score (second element of each tuple)
ranked = sorted(students, key=lambda s: s[1], reverse=True)
for name, score in ranked:
print(f"{name}: {score}")Charlie: 95
Alice: 88
Diana: 81
Bob: 74
# Lambda with map() — apply a function to each element
scores = [85, 92, 71, 68, 95]
normalized = list(map(lambda s: round(s / 100, 2), scores))
print(normalized)[0.85, 0.92, 0.71, 0.68, 0.95]
Oefeningen¶
Oefening 1 — Schrijf een for-lus die de getallen 1 t/m 30 doorloopt en voor elk getal afdrukt:
"Fizz"als het deelbaar is door 3"Buzz"als het deelbaar is door 5"FizzBuzz"als het deelbaar is door zowel 3 als 5anders het getal zelf
# your solution hereOefening 2 — Gegeven temperatures = [22.1, 18.5, -3.2, 0.0, 35.7, -10.1, 28.4]. Maak met een list comprehension twee lijsten: positive (temperaturen > 0) en negative (temperaturen ≤ 0).
temperatures = [22.1, 18.5, -3.2, 0.0, 35.7, -10.1, 28.4]
# your solution hereOefening 3 — Gegeven names = ["alice smith", "bob jones", "charlie brown"]. Maak met een list comprehension een nieuwe lijst waarbij elk naam omgezet is naar Title Case (eerste letter van elk woord groot). Gebruik de string-methode .title().
names = ["alice smith", "bob jones", "charlie brown"]
# your solution hereOefening 4 — Gebruik een dictionary comprehension en zip() om een dictionary te bouwen van de twee lijsten countries = ["Belgium", "Netherlands", "France"] en codes = ["BE", "NL", "FR"], waarbij de landnamen de waarden zijn en de codes de sleutels.
countries = ["Belgium", "Netherlands", "France"]
codes = ["BE", "NL", "FR"]
# your solution hereOefening 5 — Sorteer de lijst products = [("laptop", 999), ("mouse", 25), ("monitor", 349), ("keyboard", 89)] op prijs (tweede element) van laag naar hoog, met een lambda als sorteersleutel.
products = [("laptop", 999), ("mouse", 25), ("monitor", 349), ("keyboard", 89)]
# your solution here