๐Ÿ“ Python

The while Loop: Repeat While a Condition Holds ๐Ÿ”

P
Author
PyLand Team
๐Ÿ“…
Published
30.03.2026
โฑ๏ธ
Reading time
4 min
๐Ÿ‘๏ธ
Views
406
๐ŸŒฑ
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

๐Ÿ“

Event Loop in Python: How asyncio Enables Concurrโ€ฆ

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 386
๐Ÿ“

The for Loop: Make Python Work for You ๐Ÿ”„

Imagine that you need to display a rocket five times. You could copy print(rocket) five...

๐Ÿ“… 30.03.2026 ๐Ÿ‘๏ธ 433
๐Ÿ“

OOP: Program Like a World Builder ๐ŸŒ

Imagine: you're building a zombie-apocalypse game. You need zombies, humans, weapons. Every zombie has a...

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 413