Functies zijn herbruikbare blokken code. Ze nemen invoer aan, voeren een berekening uit en geven een resultaat terug. In deze notebook leer je functies definiëren, ze flexibel maken met parameters, en bestaande bibliotheken importeren.
Functies definiëren¶
Een functie definieer je met het sleutelwoord def. De docstring (eerste string in de functie) beschrijft wat de functie doet.
def greet(name):
"""Return a greeting for the given name."""
return f"Hello, {name}!"
print(greet("Alice"))
print(greet("Bob"))Hello, Alice!
Hello, Bob!
Parameters en standaardwaarden¶
Je kunt parameters een standaardwaarde (of default-waarde) geven. Die waarde wordt gebruikt wanneer de aanroeper het argument weglaat.
def calculate_bmi(weight_kg, height_m, verbose=True):
"""Calculate the Body Mass Index.
Parameters
----------
weight_kg : float
Weight in kilograms.
height_m : float
Height in metres.
verbose : bool, optional
If True, also print the category. Default True.
Returns
-------
float
BMI rounded to one decimal place.
"""
bmi = weight_kg / height_m**2
if verbose:
if bmi < 18.5:
category = "underweight"
elif bmi < 25:
category = "normal weight"
elif bmi < 30:
category = "overweight"
else:
category = "obese"
print(f"BMI: {bmi:.1f} ({category})")
return round(bmi, 1)
calculate_bmi(70, 1.75)
bmi_value = calculate_bmi(90, 1.80, verbose=False)
print(bmi_value)BMI: 22.9 (normal weight)
27.8
Meerdere returnwaarden¶
Python-functies kunnen meerdere waarden tegelijkertijd teruggeven via een tuple.
def summarize(values):
"""Return the minimum, maximum and mean of a list of numbers."""
return min(values), max(values), sum(values) / len(values)
data = [4, 7, 2, 9, 1, 8, 5]
minimum, maximum, mean = summarize(data) # tuple unpacking
print(f"min={minimum}, max={maximum}, mean={mean:.2f}")min=1, max=9, mean=5.14
*args en **kwargs¶
*argslaat een functie een willekeurig aantal positionele argumenten aanvaarden (als tuple).**kwargslaat een functie een willekeurig aantal sleutelwoordargumenten aanvaarden (als dictionary).
Je ziet dit patroon vaak in bibliotheken als Pandas en Matplotlib.
def total(*numbers):
"""Sum all provided numbers."""
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 1006
100
def print_info(**attributes):
"""Print keyword arguments as key-value properties."""
for key, value in attributes.items():
print(f" {key}: {value}")
print_info(name="Alice", age=22, major="AI") name: Alice
age: 22
major: AI
Scope¶
Variabelen die binnenin een functie worden aangemaakt, zijn lokaal — ze bestaan niet buiten de functie. Variabelen buiten functies zijn globaal.
threshold = 60 # global variable
def is_passing(score):
result = score >= threshold # local variable + reference to global
return result
print(is_passing(75)) # True
print(is_passing(45)) # False
# print(result) # NameError: 'result' does not exist outside the functionTrue
False
Modules importeren¶
Python’s kracht zit in zijn ecosysteem van bibliotheken. Je importeert ze met import.
Conventies die je overal in ML-code ziet:
import math # standard library
# Import a specific function
from math import pi, sqrt
import matplotlib.pyplot as plt # pyplot with alias 'plt'
import numpy as np # numpy with alias 'np'
import pandas as pd # pandas with alias 'pd'
print(math.sqrt(16)) # 4.0
print(sqrt(25)) # 5.0 — available without prefix
print(pi) # 3.14159...4.0
5.0
3.141592653589793
Hulpfuncties schrijven voor data-analyse¶
In de praktijk schrijf je regelmatig kleine hulpfuncties om herhaalde stappen te bundelen. Hier zijn twee realistische voorbeelden:
def normalize(values):
"""Scale values to the interval [0, 1] using min-max normalization.
Parameters
----------
values : list of float
The values to normalize.
Returns
-------
list of float
Normalized values between 0 and 1.
"""
min_val = min(values)
max_val = max(values)
return [(v - min_val) / (max_val - min_val) for v in values]
data = [10, 20, 30, 40, 50]
print(normalize(data)) # [0.0, 0.25, 0.5, 0.75, 1.0][0.0, 0.25, 0.5, 0.75, 1.0]
def clean_column_name(text):
"""Strip whitespace, lowercase and replace spaces with underscores.
Parameters
----------
text : str
Returns
-------
str
Cleaned string suitable as a column name.
"""
return text.strip().lower().replace(" ", "_")
column_names = ["Name Student", " Age ", "Score (%)"]
clean_names = [clean_column_name(c) for c in column_names]
print(clean_names)['name_student', 'age', 'score_(%)']
Oefeningen¶
Oefening 1 — Schrijf een functie celsius_to_fahrenheit(celsius) die een temperatuur in Celsius omzet naar Fahrenheit. Formule: F = C * 9/5 + 32. Geef de waarde terug afgerond op 1 decimaal.
# your solution hereOefening 2 — Schrijf een functie describe(values) die een lijst van getallen aanvaardt en een dictionary teruggeeft met de volgende sleutels: "n" (aantal), "min", "max", "mean", "median". Gebruik enkel ingebouwde Python-functies (sorted, len, sum, ...).
# your solution here
# Test:
# describe([3, 1, 4, 1, 5, 9, 2, 6])Oefening 3 — Schrijf een functie count_words(*sentences) die een willekeurig aantal strings accepteert en de totale woordtelling over alle zinnen teruggeeft. Gebruik *args.
# your solution here
# Test:
# count_words("hello world", "this is a test", "python is great")
# → 9Oefening 4 — Herschrijf de functie normalize() uit het notebook, maar voeg een parameter method toe die "minmax" (standaard) of "zscore" aanvaardt. Bij z-score normalisatie is de formule: z = (x - mean) / std. Tip: gebruik import math voor math.sqrt().
import math
# your solution here
# Test:
data = [10, 20, 30, 40, 50]
# normalize(data, method="minmax") → [0.0, 0.25, 0.5, 0.75, 1.0]
# normalize(data, method="zscore") → values around 0