For-loops

Introductie tot Python voor developers

Jasmin Ludolf

Senior Data Science Content Developer

Individuele vergelijkingen

# Ingrediënthoeveelheden
quantities = [500, 400, 15, 20, 30, 5]
# Waarden valideren
quantities[0] < 10
False
quantities[1] < 10
False
Introductie tot Python voor developers

For-loopsyntaxis

for value in sequence:
    action
  • Voor elke value in sequence: voer action uit

    • action is ingesprongen door de dubbele punt erboven
  • sequence = iterable, zoals list, dictionary, etc.

  • value = iterator, d.w.z. de index
    • Placeholder (naam vrij te kiezen), i is gangbaar
Introductie tot Python voor developers

Losse waarden printen

# Lijst met ingrediënten
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]


# Loop en print elk ingrediënt for ingredient in ingredients:
print(ingredient)
pasta
tomatoes
garlic
basil
olive oil
salt
Introductie tot Python voor developers

Voorwaardes in for-loops

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:
Introductie tot Python voor developers

Voorwaardes in for-loops

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:

# Check of hoeveelheid > 500 is if qty > 500: print("Ruim op voorraad") elif qty >= 100: print("Genoeg voor een kleine portie") else: print("Bijna op!")
Introductie tot Python voor developers

Voorwaardes in for-loops

Ruim op voorraad
Genoeg voor klein
Bijna op!
Bijna op!
Bijna op!
Introductie tot Python voor developers

Door strings loopen

ingredient_name = "pasta"

# Loop door elk teken for letter in ingredient_name: print(letter)
p
a
s
t
a
  • Handig om tekst te valideren, speciale tekens te checken
Introductie tot Python voor developers

Door dictionaries loopen

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}

# Loop door keys en values for item, qty in ingredients.items(): print(item, ":", qty, "grams")
pasta : 500 grams
tomatoes : 400 grams
garlic : 30 grams
  • item = key (ingrediëntnaam)
  • qty = value (hoeveelheid)
Introductie tot Python voor developers

Door dictionaries loopen

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}
factor = 2

# Schaal hoeveelheden for item, qty in ingredients.items(): scaled_qty = qty * factor print(item, ":", scaled_qty, "grams")
pasta : 1000 grams
tomatoes : 800 grams
garlic : 60 grams
Introductie tot Python voor developers

Door dictionaries loopen

# Alleen door keys loopen
for item in ingredients.keys():
    print(item)
pasta
tomatoes
garlic
# Alleen door values loopen
for qty in ingredients.values():
    print(qty, "grams")
500 grams
400 grams
30 grams
Introductie tot Python voor developers

Range

range(start, end + 1)
  • start = begingetal
  • end = eindgetal
  • Gebruikt om waarden te genereren of aan te passen
for i in range(1, 6):
    print(i)
1
2
3
4
5
Introductie tot Python voor developers

Laten we oefenen!

Introductie tot Python voor developers

Preparing Video For Download...