In deze notebook verkennen we de basis van Python: de ingebouwde datatypes en de vier container-types die je voortdurend zult gebruiken in ML.
Basis datatypesยถ
Getallenยถ
Python heeft twee numerieke types die je constant tegenkomt: int (geheel getal) en float (kommagetal). Het type van een waarde kun je opvragen met type().
x = 10
y = 3.14
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'><class 'int'>
<class 'float'>
# Arithmetic operators
print(x + 2) # addition
print(x - 3) # subtraction
print(x * 4) # multiplication
print(x / 3) # division (always returns float)
print(x // 3) # integer division
print(x % 3) # modulo (remainder)
print(x**2) # exponentiation12
7
40
3.3333333333333335
3
1
100
# Compound assignment
x += 1
print(x) # 11
x *= 2
print(x) # 2211
22
Booleansยถ
Booleans (bool) kunnen slechts twee waarden aannemen: True of False. Ze zijn het resultaat van vergelijkingen en worden gebruikt in condities.
a = True
b = False
print(a and b) # False โ both must be True
print(a or b) # True โ at least one must be True
print(not a) # False
print(a != b) # True โ exclusive OR (XOR)False
True
False
True
# Comparison operators return booleans
print(5 > 3) # True
print(5 == 5) # True
print(5 != 4) # True
print(5 >= 10) # FalseTrue
True
True
False
Stringsยถ
Strings zijn reeksen van tekens. Je kunt ze definiรซren met enkele of dubbele aanhalingstekens. F-strings (formatted string literals) zijn de meest leesbare manier om waarden in een string in te voegen.
name = "Alice"
age = 22
# F-string: insert values directly into text
print(f"{name} is {age} years old.")Alice is 22 years old.
# Useful string methods
s = " Hello, World! "
print(s.strip()) # remove leading/trailing whitespace
print(s.strip().lower()) # convert to lowercase
print(s.strip().upper()) # convert to uppercase
print(s.strip().replace("World", "Python")) # replace substring
print(s.strip().split(",")) # split on characterHello, World!
hello, world!
HELLO, WORLD!
Hello, Python!
['Hello', ' World!']
# Strings can be indexed and sliced (like lists)
word = "python"
print(word[0]) # first character: 'p'
print(word[-1]) # last character: 'n'
print(word[1:4]) # slice: 'yth'
print(len(word)) # length: 6p
n
yth
6
Containersยถ
Python heeft vier ingebouwde container-types om meerdere waarden bij te houden:
| Type | Geordend | Muteerbaar | Uniek | Gebruik |
|---|---|---|---|---|
list | โ | โ | โ | Reeksen van elementen |
dict | โ | โ | keys | key-value paren |
set | โ | โ | โ | Unieke elementen, lidmaatschapstest |
tuple | โ | โ | โ | Onveranderlijke reeksen |
Listยถ
Een list is een geordende, muteerbare reeks van elementen. Elementen mogen van verschillende types zijn.
scores = [85, 92, 78, 95, 88]
print(scores[0]) # first element: 85
print(scores[-1]) # last element: 88
print(scores[1:3]) # slice: [92, 78]
print(len(scores)) # length: 585
88
[92, 78]
5
# Adding and removing elements
scores.append(100) # add to the end
removed = scores.pop() # remove and return the last element
print(removed) # 100
print(scores)100
[85, 92, 78, 95, 88]
# Iterating over a list
animals = ["cat", "dog", "monkey"]
for animal in animals:
print(animal)
# With index via enumerate()
for i, animal in enumerate(animals):
print(f"#{i + 1}: {animal}")cat
dog
monkey
#1: cat
#2: dog
#3: monkey
# List comprehension: elegant one-liner for building lists
squares = [x**2 for x in range(6)]
print(squares) # [0, 1, 4, 9, 16, 25]
# With a condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64][0, 1, 4, 9, 16, 25]
[0, 4, 16, 36, 64]
Dictionaryยถ
Een dictionary (dict) slaat key-value paren op. Je kunt een waarde opvragen via de bijhorende key. Keys moeten uniek en onveranderlijk zijn.
student = {
"name": "Alice",
"age": 22,
"score": 91.5,
}
print(student["name"]) # 'Alice'
print("score" in student) # True โ membership test
print(student.get("year", "?")) # '?' โ safe lookup with default valueAlice
True
?
# Add, modify and delete
student["major"] = "AI" # add new key-value pair
student["score"] = 93.0 # modify value
del student["age"] # delete
print(student){'name': 'Alice', 'score': 93.0, 'major': 'AI'}
# Iterate over key-value pairs
for key, value in student.items():
print(f"{key}: {value}")name: Alice
score: 93.0
major: AI
# Dictionary comprehension
words = ["apple", "banana", "cherry"]
word_lengths = {w: len(w) for w in words}
print(word_lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}{'apple': 5, 'banana': 6, 'cherry': 6}
Setยถ
Een set is een ongeordende verzameling van unieke elementen. Ideaal voor het snel controleren van lidmaatschap en het verwijderen van duplicaten.
colors = {"red", "green", "blue"}
print("red" in colors) # True
print("yellow" in colors) # False
colors.add("yellow")
colors.add("red") # duplicate is ignored
print(colors)True
False
{'green', 'blue', 'red', 'yellow'}
# Remove duplicates from a list via set()
values = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(values))
print(unique)[1, 2, 3, 4]
Tupleยถ
Een tuple is een geordende, onveranderlijke reeks. Eens aangemaakt kunnen elementen niet meer gewijzigd worden. Tuples worden veel gebruikt om meerdere waarden tegelijk terug te geven vanuit een functie.
point = (3.5, -2.0) # x, y coordinates
x, y = point # tuple unpacking
print(f"x={x}, y={y}")
# Tuples can be used as dictionary keys (lists cannot!)
locations = {(0, 0): "origin", (1, 0): "right"}
print(locations[(0, 0)])x=3.5, y=-2.0
origin
Type-conversieยถ
Je kunt expliciet omzetten tussen types met int(), float(), str(), list(), set() en tuple().
print(int(3.9)) # 3 (truncates, does not round)
print(float("3.14")) # 3.14
print(str(42)) # '42'
print(list({1, 2, 3})) # [1, 2, 3] โ order not guaranteed
print(tuple(["a", "b", "c"])) # ('a', 'b', 'c')
# isinstance() checks the type
print(isinstance(3.14, float)) # True
print(isinstance("hello", (str, int))) # True โ checks against multiple types3
3.14
42
[1, 2, 3]
('a', 'b', 'c')
True
True
Oefening 1 โ Maak een variabele temperature met de waarde 36.6. Druk af of de temperatuur boven 37.0 is (gebruik een boolean expressie en print True of False).
# your solution hereOefening 2 โ Gegeven de string s = " Data Science 2024 ". Verwijder de spaties, zet om naar kleine letters en vervang " " door "_". Verwacht resultaat: "data_science_2024".
s = " Data Science 2024 "
# your solution hereOefening 3 โ Gegeven numbers = [4, 7, 2, 9, 1, 5, 8, 3, 6]. Maak met een list comprehension een nieuwe lijst large die alleen de getallen groter dan 5 bevat, gekwadrateerd.
numbers = [4, 7, 2, 9, 1, 5, 8, 3, 6]
# your solution hereOefening 4 โ Gegeven students = ["Alice", "Bob", "Charlie", "Alice", "Bob", "David"]. Bepaal hoeveel unieke namen er zijn (gebruik een set).
students = ["Alice", "Bob", "Charlie", "Alice", "Bob", "David"]
# your solution hereOefening 5 โ Maak een dictionary word_frequency die voor elk woord in de zin "the cat sat on the mat and the cat looked" bijhoudt hoe vaak het voorkomt. Gebruik str.split() om de woorden te scheiden. Tip: gebruik dict.get() met een standaardwaarde.
sentence = "the cat sat on the mat and the cat looked"
# your solution hereOefening 6 โ Maak een dictionary comprehension die de getallen 1 t/m 10 als sleutels gebruikt en hun kubussen (x**3) als waarden.
# your solution here