while vs for
In this tutorial, we'll choose the right loop for the situation.
Both for loops and while loops repeat code, but they are best for different situations.
Use for When You Have Items
Use for when you are looping over a collection:
names = ["Ada", "Grace", "Linus"]
for name in names:
print(name)
Use for when you know how many times to repeat:
for number in range(5):
print(number)
Use while When You Have a Condition
Use while when repetition depends on a condition:
password = ""
while password != "secret":
password = input("Password: ")
You do not know how many attempts the user will need.
Same Result, Different Style
Counting to 5 with for:
for number in range(1, 6):
print(number)
Counting to 5 with while:
number = 1
while number <= 5:
print(number)
number = number + 1
The for loop is shorter because range() handles the counting.
Quick Rule
Ask:
- Am I looping over a known collection? Use
for. - Am I repeating until something changes? Use
while.
Practice
For each task, choose for or while: print every name in a list, ask until a password is correct, print numbers 1 to 10, keep playing while lives are above zero.