The while loop: the power of repetition
Learn to use the while loop to repeat actions and avoid infinite loops.
What You'll Learn
- Understand how the while loop works and when to use it
- Write loops that stop at the right moment
- Avoid infinite loops and understand why they happen
- Use the not operator and break to control loops
A rocket sits on the launchpad. Engines ready, control team at their stations, and all that is left is the countdown: 10, 9, 8... down to zero. Nobody writes print(10), then print(9), then print(8) by hand. You tell the computer to repeat one action until you hit zero, and that is exactly what the while loop does: it runs a block of code over and over as long as a condition holds.
Your programs ran top to bottom, once. The while loop is the first time you hand the computer a job and say "keep doing this until I say stop." That one idea powers countdowns, menus that wait for input, and every game loop you will ever write.
Heroes fight, and battles do not end with a single strike. In this lesson you build the battle system of the Python Kingdom: a while loop where the hero and the monster trade blows until one falls. You also add a main menu that keeps the game alive until the player decides to quit.
In this lesson you will be able to:
- Write a
whileloop that repeats code while a condition is True - Spot and avoid infinite loops by changing the condition inside the loop
- Use
notto read conditions backwards andbreakto exit a loop on the spot - Build an interactive battle and a main menu that keep running until the player quits
How while works
The while loop repeats a block of code as long as a condition is True. The moment the condition becomes False, the loop stops and the program continues with whatever comes after it.
The structure looks like this:
while condition:
# this code repeats
# as long as condition is True
pass
Python checks the condition before each repetition. If it is True, it runs the code inside. If it is False, it skips the entire block and moves on.
Mission control checks the same question on a loop: still numbers to count down? Keep going. None left? Launch the rocket.
Example: the countdown
Here is your first while program, the rocket countdown:
What happens step by step:
secondsstarts at 10- Python checks:
10 > 0? Yes, it is True, prints 10, then decreases to 9 - Python checks:
9 > 0? Yes, prints 9, decreases to 8 - ... and so on ...
- Python checks:
1 > 0? Yes, prints 1, decreases to 0 - Python checks:
0 > 0? No, it is False. The loop stops - Prints "Launch! The rocket has lifted off!"
Two things are doing the work here. The condition (seconds > 0) decides when the loop stops. And inside the loop, the line seconds = seconds - 1 nudges the variable one step closer to the moment the condition turns False.
Drop that second line and seconds stays at 10 forever. The condition is always True, the loop never stops.
You have just written your first bug. That bug is common enough to have a name.
Infinite loops (and how to avoid them)
An infinite loop is a loop that never stops. It happens when the condition in while never becomes False.
Here is an example of an infinite loop:
[!WARNING] This loop never stops This loop runs forever on purpose. If you run it in the playground, reload the page to stop it, then add a stop condition.
The problem is clear: fuel stays at 100 forever, so fuel > 0 is always True. The program will print "Engines are running..." infinitely.
The correct version:
This will print:
Fuel remaining: 100%
Fuel remaining: 75%
Fuel remaining: 50%
Fuel remaining: 25%
Fuel depleted. Engines have stopped.
Here is the habit that saves you: every time you write a while, ask "what inside this loop eventually makes the condition False?" If you cannot point to a line, you have an infinite loop on your hands.
If you do get stuck in one here in the playground, there is no terminal and no Ctrl + C to press. Reload the page to stop it, then add the line that makes the condition turn False.
The not operator
Click pe valoare pentru a o schimba
The not operator flips a boolean value: not True becomes False, not False becomes True.
Why bother? Because sometimes the condition reads better backwards. Say the rocket cannot launch until every system is verified:
Without not, the condition would be while systems_verified == False, which works but is harder to read. With not, the code reads almost like a sentence: "while the systems are NOT verified, keep asking".
Other examples with not:
The break statement
Sometimes you need to stop a loop right now, without waiting for the condition to turn False. That is the job of break.
break exits the loop on the spot. It skips the condition check, skips the rest of the loop body, and jumps straight to the first line after the loop.
Mission control listens for commands. The moment someone sends "abort", everything stops:
See the while True? On its own that loop would run forever, but break cuts it off the moment the "abort" command arrives. You will see this pair (while True + break) everywhere in Python.
Another example: the rocket has sensors and if one detects a problem, the launch is canceled:
Combining while with input()
Pair while with input() (the function you met in the input lesson) and you get an interactive program that keeps running until the user decides to stop. This is the loop sitting underneath every menu, chat prompt, and game you have ever used.
Here is a small mission control simulator:
This one program pulls together everything from this lesson: a while loop with a condition, input() for interactivity, and break for the emergency exit.
The while loop repeats code as long as the condition is True. Always make sure something inside the loop changes the condition, otherwise you will have an infinite loop. Use break only when you need to exit immediately, not as a fix for a poorly written condition.
Exercise : The Python Kingdom battle system
Exercise : Flee from battle
Exercise : Healing potions in battle
Exercise : Main game menu
Exercise : Guess the secret number
Exercise : Password validator
Complete game code: Python Kingdom
Now your game has a main menu and a complete battle system. The hero can fight, use potions, flee, buy from the shop, and view stats:
Look closely and you will spot a problem coming. Right now the hero's stats live in separate variables (hp, attack, defense, gold), and the shop only sells one thing. Add a second potion, a sword, a shield, and you are juggling a dozen loose variables. Next lesson you pack all of that into one neat container: the list, your hero's backpack. You will fill it, dig through it, and use this same while loop to walk it item by item.
Test Your Knowledge
Check how well you understood the lesson with these 5 questions.

