Smyčky for

Introduction to Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

Jednotlivá porovnání

# Ingredient quantities
quantities = [500, 400, 15, 20, 30, 5]
# Validate values
quantities[0] < 10
False
quantities[1] < 10
False
Introduction to Python for Developers

Syntaxe smyčky for

for value in sequence:
    action
  • Pro každou value v sequence proveďte tuto action

    • action je odsazena kvůli dvojtečce na předchozím řádku
  • sequence = iterovatelný objekt, např. seznam, slovník

  • value = iterátor, tj. index
    • Zástupný název (lze pojmenovat libovolně), běžně se používá i
Introduction to Python for Developers

Tisk jednotlivých hodnot

# 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
Introduction to Python for Developers

Podmíněné příkazy ve smyčkách for

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

for qty in quantities:
Introduction to Python for Developers

Podmíněné příkazy ve smyčkách for

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!")
Introduction to Python for Developers

Podmíněné příkazy ve smyčkách for

Plenty in stock
Enough for small
Nearly out!
Nearly out!
Nearly out!
Introduction to Python for Developers

Procházení řetězců

ingredient_name = "pasta"

# Loop through each character for letter in ingredient_name: print(letter)
p
a
s
t
a
  • Užitečné pro validaci textu a hledání speciálních znaků
Introduction to Python for Developers

Procházení slovníků

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 = klíč (název ingredience)
  • qty = hodnota (množství)
Introduction to Python for Developers

Procházení slovníků

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
Introduction to Python for Developers

Procházení slovníků

# 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
Introduction to Python for Developers

Range

range(start, end + 1)
  • start = počáteční číslo
  • end = koncové číslo
  • Slouží ke generování nebo úpravě hodnot
for i in range(1, 6):
    print(i)
1
2
3
4
5
Introduction to Python for Developers

Pojďme cvičit!

Introduction to Python for Developers

Preparing Video For Download...