Victor Jeman Academy
Python Fundamentals12 min

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 while loop that repeats code while a condition is True
  • Spot and avoid infinite loops by changing the condition inside the loop
  • Use not to read conditions backwards and break to exit a loop on the spot
  • Build an interactive battle and a main menu that keep running until the player quits

How while works

Cum functioneaza while
secunde = 5
secunde > 0 ? True
True
print(secunde)
secunde = secunde - 1
↑ inapoi la conditie
False
print("Lansare!")
bucla s-a terminat
Iteratia: 0 / 5

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:

python
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:

  1. seconds starts at 10
  2. Python checks: 10 > 0? Yes, it is True, prints 10, then decreases to 9
  3. Python checks: 9 > 0? Yes, prints 9, decreases to 8
  4. ... and so on ...
  5. Python checks: 1 > 0? Yes, prints 1, decreases to 0
  6. Python checks: 0 > 0? No, it is False. The loop stops
  7. 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)

Bucla infinita vs Bucla corecta
combustibil = 100
combustibil > 0 ? True mereu!
print("Motoarele functioneaza...")
# combustibil NU se schimba!
Bucla infinita - nu se opreste niciodata!

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:

text
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

Operatorul not
not
not valoareTrue
Exemplu practic:
sisteme_verificate = False
while not sisteme_verificate: bucla continua

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

Instructiunea break
while True:
Comenzi primite: 0
↑ repeta

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

Create a battle between the hero and a Goblin. The hero has hp = 120, attack = 23 and the monster has monster_hp = 40, monster_attack = 8. In a while loop, take turns: the hero attacks the monster (subtract attack from monster_hp), then the monster attacks the hero (subtract monster_attack from hp). Display the HP of both after each round. The loop stops when one of them reaches 0 or less. At the end, announce who won.

Exercise : Flee from battle

Extend the battle system: each round, before attacking, ask the player what they want to do: "1. Attack" or "2. Flee". If they choose "2", display "You fled from battle!" and use break to exit the loop. If they choose "1", continue the battle normally. At the end, if the monster was defeated, display a victory message.

Exercise : Healing potions in battle

Add a potion system to the battle. The hero starts with potions = 2. Each round, the player can choose: "1. Attack", "2. Potion" or "3. Flee". If they choose a potion and have potions left, heal 25 HP (without exceeding max_hp = 120) and decrease the potion count. If they have no potions left, display a message. The monster attacks every round (regardless of the player's choice, except when fleeing).

Exercise : Main game menu

Create the main menu of the Python Kingdom that runs in a loop. The player can choose: "1. Fight" (displays "You search for a monster..."), "2. Shop" (displays "You enter the shop..."), "3. Stats" (displays the hero's stats) or "4. Quit game" (displays a farewell message and exits the loop). The menu repeats until the player chooses 4.

Exercise : Guess the secret number

The program picks a secret number between 1 and 50. The user must guess the number. After each attempt, the program says "Higher!" or "Lower!". When they guess correctly, display how many attempts they needed.

Hint: Python ships with extra toolboxes called modules. import random opens the one that makes random numbers. Once it is imported, random.randint(1, 50) hands you a whole number from 1 to 50, both ends included. Put import random on the very first line, then call random.randint(1, 50) to set the secret number.

Exercise : Password validator

Write a program that asks the user to create a password. The password must be at least 6 characters long. If the password is too short, display "Password too short! Minimum 6 characters." and ask again. Repeat until the user enters a valid password. At the end, display "Password set successfully!".

To count the characters in a string, use len(): len("rocket") gives back 6. So len(password) >= 6 is your "long enough?" check.

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.

Question 1 of 5

When does a while loop stop?