While loops

Introduzione a Python per sviluppatori

Jasmin Ludolf

Senior Data Science Content Developer

If statement

If statement

Flow of an if statement: start > condition met > perform action > exit

Introduzione a Python per sviluppatori

If statement versus while loop

If statement

Flow of an if statement: start > condition met > perform action > exit

While loop

Flow of a while loop: start > condition met > perform action > loop > repeat until condition is no longer met

Introduzione a Python per sviluppatori

While loop

while condition:
    action
  • Any continuous task
    • Accelerate while a button is pressed

Games console with a racing game

1 https://unsplash.com/@joaoscferrao
Introduzione a Python per sviluppatori

While loop

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")
Introduzione a Python per sviluppatori

Output

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
  • Loop exits when items_added equals ingredients_to_add
Introduzione a Python per sviluppatori

A word of caution

  • while runs continually while the condition is met
ingredients_to_add = 5
items_added = 0

while items_added < ingredients_to_add:
    remaining = ingredients_to_add - items_added
    print(remaining, "ingredients left")
Introduzione a Python per sviluppatori

Running forever

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!
  • Condition never becomes False
  • Loop runs forever, program freezes
  • Common developer mistake
Introduzione a Python per sviluppatori

Breaking a loop

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

# Terminate the loop break
  • break can also be used in for loops

  • If the code is already running: Control + C / Command + C

Introduzione a Python per sviluppatori

Conditional statements within while loops

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!")
Introduzione a Python per sviluppatori

Conditional statements output

Several ingredients remaining
Several ingredients remaining
Almost done!
Almost done!
Shopping list complete!
Introduzione a Python per sviluppatori

Let's practice!

Introduzione a Python per sviluppatori

Preparing Video For Download...