Welcome to Day 9 of the 100 Days of Python series!
Today, we’ll explore the power of while loops — a tool that helps your program repeat actions until a certain condition is no longer true.
You’ll also see how while loops are used in real-world applications, from input validation to simple games.
📦 What You'll Learn
- What a whileloop is
- How to control repetition with conditions
- Using breakandcontinue
- Real-world examples: password check, countdown, number guessing game
  
  
  🔁 What Is a while Loop?
A while loop repeats a block of code as long as a condition is True.
🧠 Syntax:
while condition:
    # do something
✅ Basic Example
count = 1
while count <= 5:
    print("Count:", count)
    count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Once count becomes 6, the loop condition count <= 5 is no longer true, so the loop stops.
🚫 Avoiding Infinite Loops
Make sure your loop condition will eventually be false — or you’ll create an infinite loop:
# ⚠️ This will run forever unless you stop it
while True:
    print("This goes on and on...")
  
  
  🛑 Using break to Exit a Loop
You can force-exit a loop using break.
while True:
    answer = input("Type 'exit' to stop: ")
    if answer == 'exit':
        print("Goodbye!")
        break
  
  
  ⏭️ Using continue to Skip an Iteration
continue skips the rest of the loop for the current iteration and jumps to the next one.
x = 0
while x < 5:
    x += 1
    if x == 3:
        continue
    print(x)
Output:
1
2
4
5
(Notice how 3 is skipped)
🔒 Real-World Example 1: Password Checker
correct_password = "python123"
attempts = 0
while attempts < 3:
    password = input("Enter password: ")
    if password == correct_password:
        print("Access granted.")
        break
    else:
        print("Wrong password.")
        attempts += 1
if attempts == 3:
    print("Too many attempts. Access denied.")
⏳ Real-World Example 2: Countdown Timer
import time
countdown = 5
while countdown > 0:
    print(countdown)
    time.sleep(1)  # Pause for 1 second
    countdown -= 1
print("Time's up!")
🎮 Real-World Example 3: Number Guessing Game
import random
number = random.randint(1, 10)
guess = 0
while guess != number:
    guess = int(input("Guess a number between 1 and 10: "))
    if guess < number:
        print("Too low!")
    elif guess > number:
        print("Too high!")
    else:
        print("Correct!")
🧠 Recap
Today you learned:
- How to use whileloops for repeating tasks
- How to use breakto stop a loop early
- How to use continueto skip an iteration
- Real-world examples like login validation and guessing games
 
 
              
 
    
Top comments (0)