Victor Jeman - Frontend Architectv3.0
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

Think of a rocket on the launchpad. The engines are ready, the control team is at their stations, and all that is left is a countdown: 10, 9, 8... down to zero. It would be absurd to write print(10), then print(9), then print(8) and so on. You need a way to repeat an action, and that is exactly what the while loop does.

Repetition is one of the most powerful tools in programming. Whenever you have something to do multiple times, while is your friend. Let's see how it works.

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 take turns hitting each other until one falls. You also add a main menu that keeps the game alive until the player decides to quit.

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:

python
while condition:
    # this code repeats
    # as long as condition is True

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.

It is like being at mission control and constantly checking: "Do we still have numbers to count? Yes? Then keep going. No? Then launch the rocket!"

Example: the countdown

Let's write our first program with while, a countdown for a rocket launch:

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!"

Notice two very important things:

  • The condition (seconds > 0) decides when the loop stops
  • Inside the loop, we modify the variable (seconds = seconds - 1) to get closer to the moment when the condition becomes False

Without that second line, seconds would stay at 10 forever, the condition would always be True, and the loop would never stop. And that brings us to the next topic...

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 (do not run this code!):

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.

Golden rule: every time you write a while loop, ask yourself: "Is there something inside the loop that makes the condition become False at some point?" If the answer is no, you have an infinite loop.

If you accidentally end up in an infinite loop, press Ctrl + C in the terminal to stop the program.

The not operator

The not operator reverses a boolean value. It is simple: not True becomes False, and not False becomes True.

Why is it useful? Because sometimes it is more natural to think about the condition "in reverse". For example, imagine the rocket cannot launch until all systems are 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 want to stop a loop immediately, without waiting for the condition to become False. That is what break is for.

break exits the loop on the spot. It does not check the condition, it does not execute anything else in the loop. The program continues with the first line after the loop.

Imagine you are at mission control and receiving commands. If someone sends "abort", everything stops immediately:

Notice that we wrote while True. This is a loop that, theoretically, would run forever. But break stops it when we receive the "abort" command. This combination (while True + break) is a very common pattern in Python.

Another example: the rocket has sensors and if one detects a problem, the launch is canceled:

Combining while with input()

One of the most useful combinations is while with input(). This lets you create interactive programs that run until the user decides to stop.

Let's build a small mission control simulator:

This program combines everything we learned: a while loop with a condition, input() for interactivity, and break so you can stop at any time.

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: use import random and random.randint(1, 50).

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!".

Complete game code: Python Kingdom (Lesson 4)

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:

Test Your Knowledge

Check how well you understood the lesson with these 5 questions.

Question 1 of 5

When does a while loop stop?