While loops

Introduction to Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

If statement

If statement

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

Introduction to Python for Developers

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

Introduction to Python for Developers

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

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

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

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

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

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

Introduction to Python for Developers

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

Conditional statements output

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

Let's practice!

Introduction to Python for Developers

Preparing Video For Download...