While loops

Introduction to Python for Developers

George Boorman

Curriculum Manager, DataCamp

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
    • Monitor while below/above a threshold

Games console with a racing game

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

While loop

# Stock limit
stock = 10


# Number of purchases num_purchases = 0
# While num_purchases < stock limit while num_purchases < stock:
# Increment num_purchases num_purchases += 1
# Print remaining stock print(stock - num_purchases)
Introduction to Python for Developers

Output

9
8
7
6
5
4
3
2
1
0
Introduction to Python for Developers

A word of caution

  • while runs continually while the condition is met
# Stock limit
stock = 10
# Number of purchases
num_purchases = 0

# While num_purchases < threshold
while num_purchases < stock:

    # Print remaining stock
    print(stock - num_purchases)
Introduction to Python for Developers

Running forever

10
10
10
10
10
10
10
10
10
10
10
10
Introduction to Python for Developers

Breaking a loop

# While num_purchases < threshold
while num_purchases < stock:

    # Print remaining stock
    print(stock - num_purchases)

# 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

# While num_purchases < threshold
while num_purchases < stock:
    # Increment num_purchases
    num_purchases += 1

# Conditional statement inside the loop if stock - num_purchases > 7: print("Plenty of stock remaining")
elif stock - num_purchases > 3: print("Some stock remaining")
elif stock - num_purchases != 0: print("Low stock!")
else: print("No stock!")
Introduction to Python for Developers

Conditional statements output

Plenty of stock remaining
Plenty of stock remaining
Some stock remaining
Some stock remaining
Some stock remaining
Some stock remaining
Low stock!
Low stock!
Low stock!
No stock!
Introduction to Python for Developers

Let's practice!

Introduction to Python for Developers

Preparing Video For Download...