for Loop vs while Loop in Python: Which One Should You Use?
Python has two kinds of loop, and beginners often wonder which to use. Both repeat code. The difference is how they know when to stop.
for: repeat a known number of times
Use for when you know in advance how many times, or when you want to go through every item in a list.
for i in range(3):
print("Attack!", i)
team = ["Pyrocub", "Pengpip", "Bellbun"]
for monster in team:
print(monster, "joins the battle")
range(3) gives 0, 1, 2. That is three numbers, starting from zero.
while: repeat until something changes
Use while when you do not know how many times. The loop keeps going as long as its condition is true.
enemy_hp = 20
while enemy_hp > 0:
enemy_hp = enemy_hp - 6
print("Enemy HP:", max(enemy_hp, 0))
print("Enemy fainted!")
Nobody told the loop "run four times". It worked that out by checking enemy_hp each round.
The infinite loop trap
If nothing inside a while loop ever makes the condition false, it runs forever:
hp = 10
while hp > 0:
print("Still fighting") # hp never changes!
Always ask: "what line inside this loop moves us toward stopping?"
Rule of thumb
- Going through a list, or a fixed count? for.
- Waiting for something to happen (HP reaches 0, the player types "quit")? while.
Anything you write with for can be written with while, but the for version is usually shorter and safer.
You can try both in the for loop and while loop lessons, where your loop literally decides how many times your monster attacks.