Smyčky while

Introduction to Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

Příkaz if

Příkaz if

Tok příkazu if: start > podmínka splněna > provedení akce > konec

Introduction to Python for Developers

Příkaz if vs. smyčka while

Příkaz if

Tok příkazu if: start > podmínka splněna > provedení akce > konec

Smyčka while

Tok smyčky while: start > podmínka splněna > provedení akce > opakování, dokud podmínka není splněna

Introduction to Python for Developers

Smyčka while

while condition:
    action
  • Jakákoli opakující se úloha
    • Akcelerovat while je stisknuto tlačítko

Herní konzole se závodní hrou

1 https://unsplash.com/@joaoscferrao
Introduction to Python for Developers

Smyčka while

ingredients_to_add = 5
items_added = 0
# Keep adding while we have items left
while items_added < ingredients_to_add:

items_added += 1 remaining = ingredients_to_add - items_added print(remaining, "ingredients left to add")
Introduction to Python for Developers

Výstup

4 ingredients left to add
3 ingredients left to add
2 ingredients left to add
1 ingredients left to add
0 ingredients left to add
  • Smyčka skončí, když items_added se rovná ingredients_to_add
Introduction to Python for Developers

Pozor

  • while běží, dokud je podmínka splněna
ingredients_to_add = 5
items_added = 0

while items_added < ingredients_to_add:
    remaining = ingredients_to_add - items_added
    print(remaining, "ingredients left")
Introduction to Python for Developers

Nekonečná smyčka

ingredients_to_add = 5
items_added = 0

# INFINITE LOOP - never exits!
while items_added < ingredients_to_add:
    remaining = ingredients_to_add - items_added
    print(remaining, "ingredients left")
    # Forgot to increment items_added!
  • Podmínka nikdy nenabude hodnoty False
  • Smyčka běží donekonečna, program zamrzne
  • Častá chyba vývojářů
Introduction to Python for Developers

Přerušení smyčky

while items_added < ingredients_to_add:
    remaining = ingredients_to_add - items_added
    print(remaining, "ingredients left")

# Terminate the loop break
  • break lze použít i ve smyčkách for

  • Pokud kód již běží: Control + C / Command + C

Introduction to Python for Developers

Podmíněné příkazy uvnitř smyček while

ingredients_to_add = 5
items_added = 0


while items_added < ingredients_to_add: items_added += 1 remaining = ingredients_to_add - items_added
if remaining > 3: print("Several ingredients remaining")
elif remaining >= 1: print("Almost done!")
else: print("Shopping list complete!")
Introduction to Python for Developers

Výstup podmíněných příkazů

Several ingredients remaining
Several ingredients remaining
Almost done!
Almost done!
Shopping list complete!
Introduction to Python for Developers

Pojďme si procvičit!

Introduction to Python for Developers

Preparing Video For Download...