Einführung in Python für die Softwareentwicklung
Jasmin Ludolf
Senior Data Science Content Developer
# Ingredient quantities
quantities = [500, 400, 15, 20, 30, 5]
# Validate values
quantities[0] < 10
False
quantities[1] < 10
False
for value in sequence:
action
für jeden wert in der sequenz ist diese aktion auszuführen
action ist im Code wegen des Doppelpunktes in der vorherigen Zeile eingerücktsequence ist ein iterierbares Objekt, z. B. eine Liste, ein Dictionary usw.
value ist der Iterator, also der Indexi ist üblich# Ingredients list ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]# Loop through and print each ingredient for ingredient in ingredients:print(ingredient)
pasta
tomatoes
garlic
basil
olive oil
salt
quantities = [1000, 800, 40, 30, 30, 15]
for qty in quantities:
quantities = [1000, 800, 40, 30, 30, 15] for qty in quantities:# Check if quantity is more than 500 if qty > 500: print("Plenty in stock") elif qty >= 100: print("Enough for a small portion") else: print("Nearly out!")
Plenty in stock
Enough for small
Nearly out!
Nearly out!
Nearly out!
ingredient_name = "pasta"# Loop through each character for letter in ingredient_name: print(letter)
p
a
s
t
a
ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}# Loop through keys and values for item, qty in ingredients.items(): print(item, ":", qty, "grams")
pasta : 500 grams
tomatoes : 400 grams
garlic : 30 grams
item = Schlüssel (Zutatenname)qty = Wert (Zutatenmenge)ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30} factor = 2# Calculate scaled quantities for item, qty in ingredients.items(): scaled_qty = qty * factor print(item, ":", scaled_qty, "grams")
pasta : 1000 grams
tomatoes : 800 grams
garlic : 60 grams
# Loop through keys only
for item in ingredients.keys():
print(item)
pasta
tomatoes
garlic
# Loop through values only
for qty in ingredients.values():
print(qty, "grams")
500 grams
400 grams
30 grams
range(start, end + 1)
start = Anfangswertend = Endwertfor i in range(1, 6):
print(i)
1
2
3
4
5
Einführung in Python für die Softwareentwicklung