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
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!