Introduction to Python for Developers
George Boorman
Curriculum Manager, DataCamp
while condition:
action
while
a button is pressedwhile
below/above a threshold# 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)
9
8
7
6
5
4
3
2
1
0
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)
10
10
10
10
10
10
10
10
10
10
10
10
# 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
# 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!")
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