Skip to main content

Repeating Code with while Loops

A for loop is great when you know in advance how many times to repeat your code.

But what if you don't know how many repetitions you need? For example:

  • Keep asking a user for their password until they type it correctly.
  • Keep running a video game while the player still has lives left.

To repeat actions based on a rule (condition), Python provides the while loop.


1. Structure of a while Loop

A while loop checks a condition. If the condition is True, it runs the code inside it. Then it checks the condition again, and runs it again. This repeats while the condition remains True.

Real-Time Example: Video Game Lives

Let's simulate a player playing a game as long as they have lives left:

lives = 3

while lives > 0:
print(f"Playing game... Lives remaining: {lives}")
# Reduce lives by 1 after each round
lives = lives - 1

print("Game Over!")

How it works:

  1. At first, lives is 3. Since 3 > 0 is True, the loop runs and subtracts 1 from lives.
  2. Next round, lives is 2. Since 2 > 0 is True, it runs again and subtracts 1.
  3. Next round, lives is 1. Since 1 > 0 is True, it runs and subtracts 1.
  4. Next round, lives is 0. Since 0 > 0 is False, Python exits the loop and prints "Game Over!".

2. ⚠️ Warning: Infinite Loops (DANGER!)

Since a while loop runs as long as the condition is True, you must make sure that the condition will eventually become False.

If the condition never becomes False, the loop will run forever! This is called an Infinite Loop, and it can lock up or freeze your computer.

# DANGER: This loop will run forever!
# counter = 1
# while counter <= 5:
# print("Stuck inside this loop!")
# # We forgot to add: counter += 1

How to Stop an Infinite Loop:

If your terminal gets stuck in an infinite loop, don't panic! Press Ctrl + C on your keyboard to instantly force the program to stop.


What's Next?

Now that we know both types of loops, what if we want to stop a loop early (like stopping a search once we find the item), or skip a specific round? Let's learn about break and continue in the next lesson!