📝 Python

The while Loop: Repeat While a Condition Holds 🔁

0
Author
04e5cc8b-58ac-4bdc-bdee-661bbb
📅
Published
30.03.2026
⏱️
Reading time
4 min
👁️
Views
94
🌱
Level
Beginner

The for loop works great when you know how many times to repeat an action. But what if you don’t?

Examples:
- A game runs while the player is alive
- Keep asking for a password until the correct one is entered
- Attack an enemy while they still have health

That’s exactly what the while loop is for.

🎯 How does while work?

Pattern:

while condition:
    # Execute code
    # as long as the condition is True

The loop checks the condition. If True — runs the code. Then checks again. Repeats until the condition becomes False.

🔢 Simple example: counter

count = 0

while count < 5:
    print(f"Count: {count}")
    count += 1

print("Done!")

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Done!

How it works:
1. count = 0 — initial value
2. Check: 0 < 5? Yes → run the body
3. Print 0, increment count to 1
4. Check: 1 < 5? Yes → run again
5. …
6. Check: 5 < 5? No → exit the loop

⚠️ Important: Always update the variable inside the loop! Otherwise you’ll get an infinite loop.

⚔️ Practical example: battle

player_health = 100
enemy_health = 80

round_number = 1

while player_health > 0 and enemy_health > 0:
    print(f"\n=== Round {round_number} ===")

    # Player attacks
    damage = 15
    enemy_health -= damage
    print(f"You attack! Enemy takes {damage} damage")
    print(f"Enemy health: {enemy_health}")

    # Check for victory
    if enemy_health <= 0:
        print("\n🎉 YOU WIN!")
        break

    # Enemy attacks
    enemy_damage = 10
    player_health -= enemy_damage
    print(f"Enemy attacks! You take {enemy_damage} damage")
    print(f"Your health: {player_health}")

    # Check for defeat
    if player_health <= 0:
        print("\n💀 YOU LOSE!")
        break

    round_number += 1

🛑 Loop control statements

break — exit the loop

break immediately stops the loop:

count = 0

while count < 100:
    print(count)
    count += 1

    if count == 5:
        print("That's enough!")
        break  # Exit the loop

print("Loop finished")

Output:

0
1
2
3
4
That's enough!
Loop finished

continue — skip the current iteration

continue jumps to the next iteration, skipping the remaining code:

count = 0

while count < 5:
    count += 1

    if count == 3:
        continue  # Skip 3

    print(count)

Output:

1
2
4
5

(3 was skipped!)

🎮 Game loop

The classic game pattern — a main loop that runs until the player loses:

game_over = False
score = 0

while not game_over:
    print(f"\n💰 Score: {score}")
    action = input("Action (attack/defend/quit): ")

    if action == "attack":
        score += 10
        print("⚔️ Successful attack! +10 points")
    elif action == "defend":
        score += 5
        print("🛡️ Defended! +5 points")
    elif action == "quit":
        print("Quitting game...")
        game_over = True
    else:
        print("❌ Unknown action!")

print(f"\nGame over! Final score: {score}")

🔄 while True — infinite loop

Sometimes you need a loop that runs forever (until it hits a break):

while True:
    user_input = input("Enter a command (or 'quit'): ")

    if user_input == "quit":
        print("Goodbye!")
        break

    print(f"You entered: {user_input}")

Useful for:
- Program menus
- Waiting for valid input
- Game loops

⚠️ The danger of infinite loops

BUG: Forgetting to update the condition variable

# ❌ DON'T DO THIS!
count = 0

while count < 5:
    print(count)
    # Forgot count += 1
    # This prints 0 forever!

Stuck in an infinite loop?
- In CodeHS: click the Stop button
- In the terminal: press Ctrl+C

🎲 Example: guess the number

import random

secret_number = random.randint(1, 10)
attempts = 0

print("I'm thinking of a number between 1 and 10")

while True:
    guess = int(input("Your guess: "))
    attempts += 1

    if guess == secret_number:
        print(f"🎉 Correct! Attempts: {attempts}")
        break
    elif guess < secret_number:
        print("⬆️ My number is higher")
    else:
        print("⬇️ My number is lower")

📊 for vs while

for while
Known number of repetitions Repeats while condition holds
for i in range(10): while health > 0:
Iterating over lists Game loops
Counter managed automatically Counter managed manually
End known in advance End depends on the condition

When to use for:
- ✅ Iterating over a list
- ✅ Repeating N times
- ✅ Fixed number of iterations

When to use while:
- ✅ Unknown number of iterations
- ✅ Depends on a condition (player alive, enemy alive)
- ✅ Waiting for user input

💪 Practical examples

Example 1: Play again

play_again = "yes"

while play_again == "yes":
    print("\n🎮 Starting game!")

    # Game logic here...
    print("Game over!")

    play_again = input("Play again? (yes/no): ")

print("Thanks for playing!")

Example 2: Health above zero

player_hp = 100

while player_hp > 0:
    print(f"\n❤️ Health: {player_hp}")

    damage = random.randint(10, 20)
    player_hp -= damage

    print(f"💥 Damage taken: {damage}")

    if player_hp <= 0:
        print("\n💀 Player defeated!")

Example 3: Input validation

while True:
    age = input("How old are you? ")

    if age.isdigit():  # Check that a number was entered
        age = int(age)
        if age > 0 and age < 150:
            print(f"You are {age} years old!")
            break
        else:
            print("❌ Age must be between 1 and 150")
    else:
        print("❌ Please enter a number!")

🎯 Summary

Construct Use
while condition: Repeat while condition is True
while True: Infinite loop (use break to exit)
break Exit the loop immediately
continue Skip the current iteration
not game_over While NOT game_over

Remember:
- ✅ while repeats as long as the condition is True
- ✅ Always update the condition variable inside the loop!
- ✅ Use break to exit
- ✅ Use continue to skip
- ✅ Don’t forget the colon : and indentation
- ✅ while True + break for menus and input waiting

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Setting Up Your Environment: Python, pip, and VS …

Before writing code locally, you need to set up three tools: Python, pip, and VS...

📅 04.06.2026 👁️ 17
📝

The datetime Module: Working with Dates and Times

datetime is Python's standard module for working with dates and times. It's part of the...

📅 08.05.2026 👁️ 67
📝

.env Files and Environment Variables: Keeping Sec…

Imagine you wrote a program with an API key hardcoded in the source and pushed...

📅 08.05.2026 👁️ 76

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!