Built with Tutify.io

    AIStudyLabs

    while Loops and Loop Control Statements

    while Loops and Loop Control Statements

    Introduction

    In previous lessons you used for loops to iterate over sequences in a predictable, countable way. In this lesson, you’ll learn how to use while loops to repeat actions as long as a condition stays true, and how to control those loops precisely with break and continue. You’ll also see common patterns with counters, sentinels, and flags that appear in real-world programs.

    By the end, you’ll be able to design safe while loops (avoiding infinite loops), exit them early when needed, skip specific iterations, and combine them with state variables for flexible control flow.


    The while Loop: Repeating While a Condition Is True

    A while loop repeatedly executes its body while a Boolean condition remains true.

    General form:

    while condition:
        # loop body
        # runs again if condition is still True
    

    The condition is checked before each iteration. When it becomes False, the loop stops.

    Example: Simple Counter with while

    counter = 1
    
    while counter <= 5:
        print("Counter:", counter)
        counter += 1
    
    # Output:
    # Counter: 1
    # Counter: 2
    # Counter: 3
    # Counter: 4
    # Counter: 5
    

    Explanation:

    When counter becomes 6, the condition is False, so the loop stops.


    Designing Safe while Loops (Avoiding Infinite Loops)

    A safe while loop always has these three elements:

    1. Initialization – set up variables before the loop.
    2. Condition – a Boolean expression that can eventually become False.
    3. Update – change variables inside the loop so the condition will eventually be False.

    If the condition never becomes False, you get an infinite loop.

    Example: Loop With Missing Update (Infinite Loop Bug)

    n = 0
    
    while n < 3:
        print("n is", n)
        # BUG: missing update like n += 1
    

    This will print forever because n stays 0, so n < 3 is always True.

    Fixed Version

    n = 0
    
    while n < 3:
        print("n is", n)
        n += 1
    
    # Output:
    # n is 0
    # n is 1
    # n is 2
    

    Always double-check that your loop variables change in a way that can make the condition false.


    Exiting Early with break

    Sometimes you want to stop a loop even if the condition is still true. Use break to exit the loop immediately.

    Example: Search Until Found (Using break)

    secret = 27
    guess = 0
    
    while guess <= 100:
        if guess == secret:
            print("Found it!", guess)
            break
        guess += 1
    else:
        # This else runs only if the while loop ends normally (no break)
        print("Secret not found in range.")
    
    # Output:
    # Found it! 27
    

    Explanation:

    Using break is common in search problems: continue looping while scanning data, then exit as soon as you find the target.


    Skipping Iterations with continue

    continue skips the rest of the loop body for the current iteration and jumps back to the condition check.

    Example: Print Only Odd Numbers with continue

    n = 0
    
    while n < 10:
        n += 1
    
        if n % 2 == 0:
            # Skip even numbers
            continue
    
        print("Odd:", n)
    
    # Output:
    # Odd: 1
    # Odd: 3
    # Odd: 5
    # Odd: 7
    # Odd: 9
    

    Explanation:

    A common mistake is to put the update after the continue, which can cause infinite loops. Always ensure your update executes regardless of continue, or design the flow so it cannot be skipped accidentally.


    Using Counters in while Loops

    Counters are very common with while when you need flexible stopping logic.

    Example: Retry with Maximum Attempts

    max_attempts = 3
    attempt = 0
    
    password = "python123"
    
    while attempt < max_attempts:
        user_input = input("Enter password: ")
        attempt += 1
    
        if user_input == password:
            print("Access granted.")
            break
        else:
            print("Incorrect password.")
    
    if attempt == max_attempts and user_input != password:
        print("Too many attempts. Access denied.")
    
    # Example Output (user enters wrong twice, then correct):
    # Enter password: test
    # Incorrect password.
    # Enter password: hello
    # Incorrect password.
    # Enter password: python123
    # Access granted.
    

    Explanation:


    Sentinel-Controlled while Loops

    A sentinel is a special value that means “stop now”. You loop until the user (or data) produces that value.

    Example: Sum Numbers Until User Enters 0 (Sentinel)

    total = 0
    
    print("Enter numbers to sum (0 to finish):")
    
    while True:
        value = int(input("> "))
    
        if value == 0:  # 0 is the sentinel
            break
    
        total += value
    
    print("Total:", total)
    
    # Example Output:
    # Enter numbers to sum (0 to finish):
    # > 10
    # > 5
    # > -3
    # > 0
    # Total: 12
    

    Explanation:

    This pattern is powerful when you don’t know how many items will arrive.


    Flag-Controlled while Loops

    A flag is a Boolean variable that represents some state, such as running = True. You update the flag in the loop to decide when to stop.

    Example: Menu Loop with Flag

    running = True
    
    while running:
        print("\nMenu:")
        print("1. Say hello")
        print("2. Say goodbye")
        print("3. Exit")
    
        choice = input("Choose an option (1-3): ")
    
        if choice == "1":
            print("Hello!")
        elif choice == "2":
            print("Goodbye!")
        elif choice == "3":
            print("Exiting program...")
            running = False  # update flag to stop loop
        else:
            print("Invalid choice. Try again.")
    
    # Example Output (user chooses 1, then 3):
    # Menu:
    # 1. Say hello
    # 2. Say goodbye
    # 3. Exit
    # Choose an option (1-3): 1
    # Hello!
    #
    # Menu:
    # 1. Say hello
    # 2. Say goodbye
    # 3. Exit
    # Choose an option (1-3): 3
    # Exiting program...
    

    Explanation:

    Flag-controlled loops are useful when multiple conditions can stop the loop, not just one counter or one sentinel value.


    Combining Patterns: Counter + Flag + break

    In real programs you often mix these techniques.

    Example: Limited-Guess Number Game

    secret = 15
    max_guesses = 5
    
    attempt = 0
    won = False
    
    while attempt < max_guesses and not won:
        guess = int(input("Guess the number (1-20): "))
        attempt += 1
    
        if guess == secret:
            print("Correct! You won in", attempt, "guesses.")
            won = True
        elif guess < secret:
            print("Too low.")
        else:
            print("Too high.")
    
    if not won:
        print("Out of guesses. The number was", secret)
    
    # Example Output:
    # Guess the number (1-20): 10
    # Too low.
    # Guess the number (1-20): 18
    # Too high.
    # Guess the number (1-20): 15
    # Correct! You won in 3 guesses.
    

    Explanation:


    Summary / Key Takeaways

    In this lesson on while Loops and Loop Control Statements, you have learned:

    Python Programming – Complete Course with Practical Examples — Loops and Iteration Patterns

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found