Python While Loops

Master repetitive tasks with condition-based loops

šŸ”„ What are While Loops?

While loops execute a block of code repeatedly as long as a specified condition remains true. They're perfect when you don't know exactly how many times you need to repeat something, but you know when to stop.


# Basic while loop example
counter = 1
while counter <= 2:
    print(f"Count: {counter}")
    counter += 1    # Increment counter

# Result:
# Count: 1
# Count: 2 
                                    
while
Keyword
Condition
Based
Flexible
Iteration

Basic While Loop Structure

A while loop continues executing as long as the condition is True :

Basic While Loop
# Basic counting with while loop
count = 1
while count <= 5:
    print(f"Count is: {count}")
    count += 1  # Important: increment to avoid infinite loop

print("Loop finished!")

# Countdown example
countdown = 5
print("Rocket launch countdown:")
while countdown > 0:
    print(f"{countdown}...")
    countdown -= 1
print("šŸš€ Blast off!")

# Simple user input validation
password = ""
while password != "secret123":
    password = input("Enter the password: ")
    if password != "secret123":
        print("Incorrect password. Try again.")

print("Access granted!")

āš ļø Avoiding Infinite Loops:

  • Always ensure the condition can become False
  • Update the variable(s) used in the condition inside the loop
  • Use Ctrl+C to stop a runaway loop

Loop Control: break and continue

Control the flow of your loops with break and continue statements:

šŸ›‘

break Statement

Exits the loop immediately

ā­ļø

continue Statement

Skips to the next iteration

Break and Continue Examples
# Using break to exit early
print("=== BREAK Example ===")
number = 1
while number <= 10:
    if number == 6:
        print(f"Found {number}! Breaking out of loop.")
        break
    print(f"Number: {number}")
    number += 1
print("Loop ended.")

print("\n=== CONTINUE Example ===")
# Using continue to skip iterations
counter = 0
while counter < 10:
    counter += 1
    if counter % 2 == 0:  # Skip even numbers
        continue
    print(f"Odd number: {counter}")

print("\n=== PRACTICAL Example: Number Guessing Game ===")
import random

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

print("šŸŽÆ Guess the number between 1 and 10!")
print(f"You have {max_attempts} attempts.")

while attempts < max_attempts:
    try:
        guess = int(input(f"Attempt {attempts + 1}: Enter your guess: "))
        attempts += 1
        
        if guess == secret_number:
            print(f"šŸŽ‰ Congratulations! You guessed it in {attempts} attempts!")
            break
        elif guess < secret_number:
            print("šŸ“ˆ Too low!")
        else:
            print("šŸ“‰ Too high!")
        
        if attempts < max_attempts:
            print(f"You have {max_attempts - attempts} attempts left.")
    
    except ValueError:
        print("āŒ Please enter a valid number!")
        continue

if attempts == max_attempts and guess != secret_number:
    print(f"šŸ˜ž Game over! The number was {secret_number}.")

print("\n=== SEARCH Example ===")
# Finding an item in a list
shopping_list = ["apples", "bread", "milk", "eggs", "cheese", "butter"]
search_item = "milk"

index = 0
found = False

while index < len(shopping_list):
    if shopping_list[index] == search_item:
        print(f"āœ… Found '{search_item}' at position {index + 1}")
        found = True
        break
    index += 1

if not found:
    print(f"āŒ '{search_item}' not found in the shopping list")

The while-else Statement

Python's while loops can have an optional else clause that executes when the loop completes normally (not via break):

While-Else Examples
# Example 1: Normal completion (else executes)
print("=== Normal Loop Completion ===")
count = 1
while count <= 3:
    print(f"Count: {count}")
    count += 1
else:
    print("āœ… Loop completed normally!")

print("\n=== Loop with Break (else doesn't execute) ===")
count = 1
while count <= 5:
    print(f"Count: {count}")
    if count == 3:
        print("Breaking out of loop!")
        break
    count += 1
else:
    print("āœ… This won't be printed because of break")

print("\n=== Practical Example: Prime Number Checker ===")
def is_prime(number):
    """Check if a number is prime using while-else"""
    if number < 2:
        return False
    
    divisor = 2
    while divisor * divisor <= number:
        if number % divisor == 0:
            return False  # Found a divisor, not prime
        divisor += 1
    else:
        return True  # No divisors found, it's prime

# Test prime checker
test_numbers = [2, 3, 4, 9, 11, 13, 15, 17, 20, 23]
print("Prime number check:")
for num in test_numbers:
    result = "āœ… Prime" if is_prime(num) else "āŒ Not prime"
    print(f"{num}: {result}")

print("\n=== Search with while-else ===")
def find_item_position(items, target):
    """Find item position using while-else"""
    position = 0
    while position < len(items):
        if items[position] == target:
            return f"Found '{target}' at position {position}"
        position += 1
    else:
        return f"'{target}' not found in the list"

# Test the search function
fruits = ["apple", "banana", "orange", "grape", "kiwi"]
print(find_item_position(fruits, "orange"))  # Found
print(find_item_position(fruits, "mango"))   # Not found

Nested While Loops

You can nest while loops inside other while loops for complex iteration patterns:

Nested While Loops
# Simple multiplication table
print("=== MULTIPLICATION TABLE ===")
row = 1
while row <= 5:
    col = 1
    while col <= 5:
        product = row * col
        print(f"{product:3d}", end=" ")
        col += 1
    print()  # New line after each row
    row += 1

print("\n=== PATTERN PRINTING ===")
# Print a triangle pattern
rows = 5
current_row = 1

while current_row <= rows:
    # Print spaces for alignment
    spaces = rows - current_row
    space_count = 0
    while space_count < spaces:
        print(" ", end="")
        space_count += 1
    
    # Print stars
    stars = 0
    while stars < current_row:
        print("* ", end="")
        stars += 1
    
    print()  # New line
    current_row += 1

print("\n=== MATRIX OPERATIONS ===")
# Create and display a matrix
def create_matrix(rows, cols, fill_value=0):
    """Create a matrix using nested while loops"""
    matrix = []
    row = 0
    while row < rows:
        current_row = []
        col = 0
        while col < cols:
            current_row.append(fill_value)
            col += 1
        matrix.append(current_row)
        row += 1
    return matrix

def display_matrix(matrix):
    """Display matrix using nested while loops"""
    row = 0
    while row < len(matrix):
        col = 0
        while col < len(matrix[row]):
            print(f"{matrix[row][col]:3d}", end=" ")
            col += 1
        print()
        row += 1

def fill_matrix_with_pattern(matrix):
    """Fill matrix with a pattern"""
    row = 0
    while row < len(matrix):
        col = 0
        while col < len(matrix[row]):
            matrix[row][col] = (row + 1) * (col + 1)
            col += 1
        row += 1

# Create and manipulate matrix
my_matrix = create_matrix(4, 5)
fill_matrix_with_pattern(my_matrix)
print("Matrix with pattern:")
display_matrix(my_matrix)

print("\n=== GAME BOARD EXAMPLE ===")
# Simple tic-tac-toe board
def create_game_board():
    """Create a 3x3 game board"""
    board = []
    row = 0
    while row < 3:
        board_row = []
        col = 0
        while col < 3:
            board_row.append("-")
            col += 1
        board.append(board_row)
        row += 1
    return board

def display_board(board):
    """Display the game board"""
    print("  0 1 2")
    row = 0
    while row < len(board):
        print(f"{row} ", end="")
        col = 0
        while col < len(board[row]):
            print(f"{board[row][col]} ", end="")
            col += 1
        print()
        row += 1

# Create and display game board
game_board = create_game_board()
# Add some moves
game_board[0][0] = "X"
game_board[1][1] = "O"
game_board[2][2] = "X"

print("Tic-tac-toe board:")
display_board(game_board)

Real-World Applications

Here are practical examples showing how while loops solve real programming problems:

Real-World While Loop Applications
"""
Real-World While Loop Applications
"""

import random
import time

# 1. ATM Simulation
def atm_simulation():
    """Simulate an ATM machine interface"""
    balance = 1000.00
    pin = "1234"
    max_attempts = 3
    
    print("šŸ§ Welcome to PyBank ATM")
    print("=" * 30)
    
    # PIN verification
    attempts = 0
    while attempts < max_attempts:
        entered_pin = input("Enter your PIN: ")
        if entered_pin == pin:
            print("āœ… PIN accepted!")
            break
        else:
            attempts += 1
            remaining = max_attempts - attempts
            if remaining > 0:
                print(f"āŒ Incorrect PIN. {remaining} attempts remaining.")
            else:
                print("āŒ Too many incorrect attempts. Card blocked.")
                return
    
    # ATM operations
    while True:
        print(f"\nCurrent Balance: ${balance:.2f}")
        print("\n1. Check Balance")
        print("2. Withdraw Money")
        print("3. Deposit Money")
        print("4. Exit")
        
        choice = input("\nSelect an option (1-4): ")
        
        if choice == "1":
            print(f"šŸ’° Your current balance is: ${balance:.2f}")
        
        elif choice == "2":
            try:
                amount = float(input("Enter withdrawal amount: $"))
                if amount <= 0:
                    print("āŒ Invalid amount!")
                elif amount > balance:
                    print("āŒ Insufficient funds!")
                else:
                    balance -= amount
                    print(f"āœ… Withdrawal successful! New balance: ${balance:.2f}")
            except ValueError:
                print("āŒ Please enter a valid amount!")
        
        elif choice == "3":
            try:
                amount = float(input("Enter deposit amount: $"))
                if amount <= 0:
                    print("āŒ Invalid amount!")
                else:
                    balance += amount
                    print(f"āœ… Deposit successful! New balance: ${balance:.2f}")
            except ValueError:
                print("āŒ Please enter a valid amount!")
        
        elif choice == "4":
            print("šŸ‘‹ Thank you for using PyBank ATM!")
            break
        
        else:
            print("āŒ Invalid option! Please try again.")

# 2. File Processing Simulation
def process_log_file():
    """Simulate processing a log file line by line"""
    # Simulate log entries
    log_entries = [
        "2024-01-15 10:30:00 INFO User login successful",
        "2024-01-15 10:31:15 WARNING High memory usage detected",
        "2024-01-15 10:32:30 ERROR Database connection failed",
        "2024-01-15 10:33:45 INFO User logout",
        "2024-01-15 10:34:00 ERROR File not found",
        "2024-01-15 10:35:15 INFO System backup completed",
    ]
    
    print("šŸ“„ LOG FILE PROCESSOR")
    print("=" * 40)
    
    line_number = 0
    error_count = 0
    warning_count = 0
    info_count = 0
    
    while line_number < len(log_entries):
        line = log_entries[line_number]
        print(f"Processing line {line_number + 1}: {line}")
        
        # Analyze log level
        if "ERROR" in line:
            error_count += 1
            print("  🚨 Error detected!")
        elif "WARNING" in line:
            warning_count += 1
            print("  āš ļø  Warning detected!")
        elif "INFO" in line:
            info_count += 1
            print("  ā„¹ļø  Info message")
        
        line_number += 1
        time.sleep(0.5)  # Simulate processing time
    
    print(f"\nšŸ“Š PROCESSING SUMMARY:")
    print(f"Total lines processed: {line_number}")
    print(f"Errors: {error_count}")
    print(f"Warnings: {warning_count}")
    print(f"Info messages: {info_count}")

# 3. Simple Web Crawler Simulation
def web_crawler_simulation():
    """Simulate a simple web crawler"""
    urls_to_visit = [
        "https://example.com",
        "https://example.com/about",
        "https://example.com/products",
        "https://example.com/contact",
        "https://example.com/blog"
    ]
    
    visited_urls = []
    failed_urls = []
    
    print("šŸ•·ļø  WEB CRAWLER SIMULATION")
    print("=" * 40)
    
    index = 0
    while index < len(urls_to_visit):
        current_url = urls_to_visit[index]
        print(f"\n🌐 Crawling: {current_url}")
        
        # Simulate network request (random success/failure)
        success = random.choice([True, True, True, False])  # 75% success rate
        
        if success:
            print(f"  āœ… Successfully crawled {current_url}")
            visited_urls.append(current_url)
            
            # Simulate finding new URLs
            if random.choice([True, False]):
                new_url = f"{current_url}/page{random.randint(1, 10)}"
                if new_url not in urls_to_visit and new_url not in visited_urls:
                    urls_to_visit.append(new_url)
                    print(f"  šŸ”— Found new URL: {new_url}")
        else:
            print(f"  āŒ Failed to crawl {current_url}")
            failed_urls.append(current_url)
        
        index += 1
        time.sleep(0.3)  # Simulate crawl delay
        
        # Stop if we've crawled enough
        if len(visited_urls) >= 8:
            print("\nšŸ›‘ Crawl limit reached!")
            break
    
    print(f"\nšŸ“Š CRAWL SUMMARY:")
    print(f"URLs successfully crawled: {len(visited_urls)}")
    print(f"URLs failed: {len(failed_urls)}")
    print(f"URLs remaining: {len(urls_to_visit) - index}")

# 4. Data Validation Loop
def validate_user_registration():
    """Validate user registration data"""
    print("šŸ“ USER REGISTRATION")
    print("=" * 30)
    
    # Username validation
    while True:
        username = input("Enter username (3-20 characters, letters/numbers only): ")
        if len(username) < 3:
            print("āŒ Username too short!")
        elif len(username) > 20:
            print("āŒ Username too long!")
        elif not username.isalnum():
            print("āŒ Username can only contain letters and numbers!")
        else:
            print("āœ… Username accepted!")
            break
    
    # Email validation (simplified)
    while True:
        email = input("Enter email address: ")
        if "@" not in email or "." not in email:
            print("āŒ Invalid email format!")
        elif len(email) < 5:
            print("āŒ Email too short!")
        else:
            print("āœ… Email accepted!")
            break
    
    # Password validation
    while True:
        password = input("Enter password (min 8 characters, must include number): ")
        if len(password) < 8:
            print("āŒ Password too short!")
        elif not any(char.isdigit() for char in password):
            print("āŒ Password must contain at least one number!")
        else:
            print("āœ… Password accepted!")
            break
    
    # Age validation
    while True:
        try:
            age = int(input("Enter your age: "))
            if age < 13:
                print("āŒ Must be at least 13 years old!")
            elif age > 120:
                print("āŒ Invalid age!")
            else:
                print("āœ… Age accepted!")
                break
        except ValueError:
            print("āŒ Please enter a valid number!")
    
    print(f"\nšŸŽ‰ Registration successful!")
    print(f"Welcome, {username}!")

# 5. Simple Game: Guess the Number with Statistics
def advanced_guessing_game():
    """Advanced number guessing game with statistics"""
    print("šŸŽÆ ADVANCED GUESSING GAME")
    print("=" * 40)
    
    games_played = 0
    total_attempts = 0
    best_score = float('inf')
    
    while True:
        # Start new game
        secret_number = random.randint(1, 100)
        attempts = 0
        max_attempts = 7
        games_played += 1
        
        print(f"\nšŸŽ® Game {games_played}")
        print(f"Guess the number between 1 and 100!")
        print(f"You have {max_attempts} attempts.")
        
        while attempts < max_attempts:
            try:
                guess = int(input(f"\nAttempt {attempts + 1}: "))
                attempts += 1
                
                if guess == secret_number:
                    print(f"šŸŽ‰ Correct! You guessed it in {attempts} attempts!")
                    total_attempts += attempts
                    if attempts < best_score:
                        best_score = attempts
                        print("šŸ† New best score!")
                    break
                elif guess < secret_number:
                    difference = secret_number - guess
                    if difference <= 5:
                        print("šŸ”„ Very close! Go higher!")
                    elif difference <= 15:
                        print("šŸ“ˆ Close! Go higher!")
                    else:
                        print("šŸ“ˆ Too low!")
                else:
                    difference = guess - secret_number
                    if difference <= 5:
                        print("šŸ”„ Very close! Go lower!")
                    elif difference <= 15:
                        print("šŸ“‰ Close! Go lower!")
                    else:
                        print("šŸ“‰ Too high!")
                
                remaining = max_attempts - attempts
                if remaining > 0:
                    print(f"Attempts remaining: {remaining}")
                
            except ValueError:
                print("āŒ Please enter a valid number!")
                continue
        
        if attempts == max_attempts and guess != secret_number:
            print(f"šŸ˜ž Game over! The number was {secret_number}")
            total_attempts += attempts
        
        # Show statistics
        avg_attempts = total_attempts / games_played
        print(f"\nšŸ“Š STATISTICS:")
        print(f"Games played: {games_played}")
        print(f"Average attempts: {avg_attempts:.1f}")
        if best_score != float('inf'):
            print(f"Best score: {best_score} attempts")
        
        # Play again?
        while True:
            play_again = input("\nPlay again? (y/n): ").lower()
            if play_again in ['y', 'yes']:
                break
            elif play_again in ['n', 'no']:
                print("šŸ‘‹ Thanks for playing!")
                return
            else:
                print("Please enter 'y' or 'n'")

# Demo function to run examples
def demo_while_loops():
    """Demonstrate various while loop applications"""
    print("šŸ”„ WHILE LOOPS DEMO")
    print("=" * 50)
    
    demos = {
        "1": ("ATM Simulation", atm_simulation),
        "2": ("Log File Processor", process_log_file),
        "3": ("Web Crawler", web_crawler_simulation),
        "4": ("User Registration", validate_user_registration),
        "5": ("Guessing Game", advanced_guessing_game)
    }
    
    while True:
        print("\nSelect a demo:")
        for key, (name, _) in demos.items():
            print(f"{key}. {name}")
        print("6. Exit")
        
        choice = input("\nEnter your choice (1-6): ")
        
        if choice in demos:
            print(f"\n{'='*50}")
            demos[choice][1]()
            print(f"{'='*50}")
        elif choice == "6":
            print("šŸ‘‹ Goodbye!")
            break
        else:
            print("āŒ Invalid choice! Please try again.")

# Uncomment to run the demo
# demo_while_loops()

🧠 Test Your Knowledge

Test your understanding of Python while loops:

Question 1: What happens if the condition in a while loop never becomes False?

Question 2: What does the 'break' statement do in a while loop?

Question 3: When does the 'else' clause of a while loop execute?