Python While Loops and Loop Control: Condition-Based Repetition

Lesson Overview

Master Python while loops and understand when to use them over for loops. Learn about do-while loop simulation, the critical importance of loop termination, and control flow with break and continue statements through practical real-world examples.

Lesson Content

Understanding While Loops vs For Loops

You've already learned about for loops that work perfectly with ranges and known sequences. But programming has another type of loop: the while loop.

Key Difference:

  • For loops: Used when you know exactly how many times to repeat (iterate over a sequence)
  • While loops: Used when you want to repeat based on a condition, not a fixed count

For Loop Recap

# For loop - we know exactly how many times
for i in range(5):
    print(f"Count: {i}")
# Runs exactly 5 times: 0, 1, 2, 3, 4

While Loop Introduction

# While loop - we repeat based on a condition
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1  # Important: update the condition variable
# Runs while count is less than 5

When to Use While Loops

While loops are ideal for scenarios where:

  • User input validation: Keep asking until valid input is provided
  • Game loops: Continue until game over condition
  • Menu systems: Show menu until user chooses to exit
  • Processing unknown data: Read file until end of file
  • Retry mechanisms: Keep trying an operation until it succeeds

Real-World Example: ATM PIN Validation

# We don't know how many attempts user will need
correct_pin = "1234"
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    user_pin = input("Enter your PIN: ")
    
    if user_pin == correct_pin:
        print("Access granted!")
        break  # Exit the loop
    else:
        attempts += 1
        remaining = max_attempts - attempts
        print(f"Incorrect PIN. {remaining} attempts remaining.")

if attempts >= max_attempts:
    print("Account locked due to too many failed attempts.")

Traditional While Loop

# Standard while loop - condition checked first
number = 10
while number < 5:
    print("This won't print because 10 is not less than 5")
    number += 1

 

The Critical Importance of Loop Termination

Every loop must have a way to stop, or it becomes an infinite loop. This is one of the most important concepts in programming.

What Makes a Loop Terminate

  • Condition becomes False: The while condition evaluates to False
  • Break statement: Explicitly exit the loop
  • Return statement: Exit from the function (and thus the loop)
  • Exception/Error: Program stops due to an error

Example of Proper Termination

# Proper termination - condition will eventually become False
countdown = 5
while countdown > 0:
    print(f"Countdown: {countdown}")
    countdown -= 1  # This ensures the loop will end
print("Blast off!")

What Happens if Loops Don't End

Infinite loops can cause serious problems:

  • System freeze: Computer becomes unresponsive
  • Memory consumption: Program uses more and more memory
  • CPU overload: Processor works at 100% capacity
  • Application crash: Operating system may kill the program
  • Battery drain: On mobile devices, infinite loops drain battery quickly

Common Infinite Loop Mistakes

# DANGER: Infinite loop - condition never changes
count = 1
while count <= 5:
    print(f"Count: {count}")
    # Missing: count += 1
    # This loop will run forever!

# DANGER: Infinite loop - wrong condition update  
number = 0
while number < 10:
    print(number)
    number -= 1  # This makes number more negative, never reaches 10!

# DANGER: Infinite loop - condition never becomes False
while True:
    print("This runs forever")
    # No break statement or way to exit

How to Avoid Infinite Loops

  1. Always update condition variables: Make sure variables in the condition change
  2. Include break statements: For complex conditions, have explicit exit points
  3. Add safety counters: Limit maximum iterations
  4. Test your logic: Walk through the loop mentally before running

Loop Control: Break and Continue

Python provides two powerful statements to control loop execution:

Break Statement

The break statement immediately exits the loop, regardless of the condition.

# Break example: Find first even number
numbers = [1, 3, 7, 8, 9, 12, 15]
index = 0

while index < len(numbers):
    if numbers[index] % 2 == 0:
        print(f"First even number found: {numbers[index]}")
        break  # Exit the loop immediately
    index += 1
else:
    print("No even number found")

Continue Statement

The continue statement skips the rest of the current iteration and moves to the next one.

# Continue example: Print only positive numbers
numbers = [-2, 5, -1, 8, 0, 3, -4]
index = 0

while index < len(numbers):
    if numbers[index] <= 0:
        index += 1
        continue  # Skip negative numbers and zero
    
    print(f"Positive number: {numbers[index]}")
    index += 1

Why Break and Continue are Useful

  • Early exit: Stop processing when you find what you need
  • Skip invalid data: Continue processing valid items, skip invalid ones
  • Error handling: Break out of loops when errors occur
  • Performance: Avoid unnecessary computations
  • Clean code: Make loop logic clearer and more readable

Real-World Example: Simple Banking System

Let's build a complete example that demonstrates while loops, break, continue, and proper termination:

# Simple Banking System
def banking_system():
    balance = 1000.0
    transaction_count = 0
    max_transactions = 10
    
    print("Welcome to Simple Bank!")
    print(f"Your current balance: Rs.{balance}")
    
    while True:
        # Safety check - prevent too many transactions
        if transaction_count >= max_transactions:
            print(f"Maximum {max_transactions} transactions reached. Session ended.")
            break
        
        print("\n--- Banking Menu ---")
        print("1. Check Balance")
        print("2. Deposit Money") 
        print("3. Withdraw Money")
        print("4. Exit")
        
        choice = input("Choose an option (1-4): ").strip()
        
        # Skip invalid input
        if choice not in ['1', '2', '3', '4']:
            print("Invalid choice. Please try again.")
            continue
        
        transaction_count += 1
        
        if choice == '1':
            # Check Balance
            print(f"Your current balance: Rs.{balance}")
        
        elif choice == '2':
            # Deposit Money
            try:
                amount = float(input("Enter deposit amount: Rs."))
                if amount <= 0:
                    print("Deposit amount must be positive.")
                    continue
                
                balance += amount
                print(f"Rs.{amount} deposited successfully!")
                print(f"New balance: Rs.{balance}")
            
            except ValueError:
                print("Invalid amount. Please enter a number.")
                continue
        
        elif choice == '3':
            # Withdraw Money
            try:
                amount = float(input("Enter withdrawal amount: Rs."))
                if amount <= 0:
                    print("Withdrawal amount must be positive.")
                    continue
                
                if amount > balance:
                    print("Insufficient balance!")
                    continue
                
                balance -= amount
                print(f"Rs.{amount} withdrawn successfully!")
                print(f"New balance: Rs.{balance}")
            
            except ValueError:
                print("Invalid amount. Please enter a number.")
                continue
        
        elif choice == '4':
            # Exit
            print("Thank you for using Simple Bank!")
            print(f"Final balance: Rs.{balance}")
            break  # Exit the main loop
        
        # Ask if user wants to continue (additional safety)
        if transaction_count >= max_transactions - 1:
            print("Warning: This is your last transaction.")
    
    print(f"Total transactions completed: {transaction_count}")

# Run the banking system
banking_system()

Practical Loop Exercises

Exercise 1: Number Guessing Game

# Number Guessing Game
import random

def guessing_game():
    secret_number = random.randint(1, 100)
    attempts = 0
    max_attempts = 7
    
    print("I'm thinking of a number between 1 and 100!")
    print(f"You have {max_attempts} attempts to guess it.")
    
    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 {secret_number} in {attempts} attempts!")
                break
            elif guess < secret_number:
                print("Too low!")
            else:
                print("Too high!")
            
            remaining = max_attempts - attempts
            if remaining > 0:
                print(f"You have {remaining} attempts left.")
        
        except ValueError:
            print("Please enter a valid number.")
            attempts -= 1  # Don't count invalid input as an attempt
            continue
    
    else:
        print(f"Game over! The secret number was {secret_number}")

# Uncomment to play:
# guessing_game()

Exercise 2: Input Validation System

# Input Validation System
def get_valid_email():
    while True:
        email = input("Enter your email address: ").strip()
        
        # Basic email validation
        if '@' not in email:
            print("Error: Email must contain '@' symbol")
            continue
        
        if email.count('@') != 1:
            print("Error: Email must contain exactly one '@' symbol")
            continue
        
        username, domain = email.split('@')
        
        if len(username) < 1:
            print("Error: Username part cannot be empty")
            continue
        
        if '.' not in domain:
            print("Error: Domain must contain at least one dot")
            continue
        
        if len(domain.split('.')[0]) < 1:
            print("Error: Domain name cannot be empty")
            continue
        
        # If all validations pass
        print(f"Valid email accepted: {email}")
        return email

# Uncomment to test:
# valid_email = get_valid_email()

Exercise 3: Simple Calculator with Loop

# Simple Calculator
def calculator():
    print("Simple Calculator")
    print("Operations: +, -, *, /")
    print("Type 'quit' to exit")
    
    while True:
        expression = input("\nEnter calculation (e.g., 5 + 3): ").strip()
        
        if expression.lower() == 'quit':
            print("Calculator closed. Goodbye!")
            break
        
        try:
            # Simple parsing - split by spaces
            parts = expression.split()
            
            if len(parts) != 3:
                print("Error: Please use format: number operator number")
                continue
            
            num1 = float(parts[0])
            operator = parts[1]
            num2 = float(parts[2])
            
            if operator == '+':
                result = num1 + num2
            elif operator == '-':
                result = num1 - num2
            elif operator == '*':
                result = num1 * num2
            elif operator == '/':
                if num2 == 0:
                    print("Error: Cannot divide by zero")
                    continue
                result = num1 / num2
            else:
                print(f"Error: Unknown operator '{operator}'")
                continue
            
            print(f"Result: {num1} {operator} {num2} = {result}")
        
        except ValueError:
            print("Error: Please enter valid numbers")
            continue
        except Exception as e:
            print(f"Unexpected error: {e}")
            continue

# Uncomment to run:
# calculator()

Key Takeaways

  • While loops repeat based on conditions, not fixed counts
  • For loops are better for known sequences, while loops for unknown iterations
  • Do-while behavior can be simulated with while True and break
  • Loop termination is critical - always ensure loops can end
  • Infinite loops can crash systems and waste resources
  • Break statement exits loops immediately
  • Continue statement skips to next iteration
  • Safety measures like maximum iteration counts prevent problems

Best Practices

  1. Always update condition variables inside while loops
  2. Use break and continue to make complex loop logic clearer
  3. Add safety limits to prevent infinite loops
  4. Test edge cases - what happens with empty input, zero values, etc.
  5. Choose the right loop type - for for sequences, while for conditions
  6. Handle exceptions gracefully within loops
  7. Keep loop bodies simple - extract complex logic into functions

Coming Up Next

Excellent work! You now understand both for loops and while loops, and know how to control their execution with break and continue statements. You've also learned the critical importance of proper loop termination.

In our next lesson, we'll explore Data Collections: Lists and Tuples - learning how to store and organize multiple pieces of data in single variables, and how to use loops to process collections efficiently.

You're building a solid foundation in programming logic and control flow!