Loop Conditions
In this tutorial, we'll control exactly when a while loop continues.
The condition controls how long a while loop continues.
lives = 3
while lives > 0:
print("Keep playing")
lives = lives - 1
The loop runs while lives > 0 is true.
Check Before Running
A while loop checks the condition before the loop body runs.
count = 10
while count < 5:
print("This will not print")
The condition is false at the start, so the body never runs.
Off-by-One Errors
Be careful with < and <=.
count = 1
while count < 5:
print(count)
count = count + 1
This prints 1 to 4, not 1 to 5.
To include 5:
while count <= 5:
print(count)
count = count + 1
Combining Conditions
You can use and or or:
attempts = 0
password = ""
while password != "secret" and attempts < 3:
password = input("Password: ")
attempts = attempts + 1
This loop stops when either the password is correct or the attempts reach 3. When conditions are combined, read them slowly in plain English.
Print the Condition Values
If a loop surprises you, print the values used in the condition:
print("attempts:", attempts)
print("password:", password)
This usually reveals why the loop continued or stopped.
Practice
Write a loop that counts from 2 to 10, including 10.