Built with Tutify.io

    AIStudyLabs

    break, continue, and else with Loops

    break, continue, and else with Loops

    Introduction

    In this lesson, you will deepen your understanding of loop control in Python using three powerful tools:

    You already know how for and while loops work. Now you will learn how to control when and how they stop or skip work, and how to reason about complex flows using these statements together.


    Using break to Exit Loops Early

    break immediately stops the nearest enclosing loop, regardless of the loop’s condition.

    Example: Stop Searching When Found

    numbers = [3, 7, 11, 15, 21, 28]
    target = 15
    
    for n in numbers:
        if n == target:
            print("Found target:", n)
            break
        print("Checked:", n)
    
    # Output
    Checked: 3
    Checked: 7
    Checked: 11
    Found target: 15
    

    Explanation:

    Use break when continuing the loop would be unnecessary or inefficient.


    Using continue to Skip the Current Iteration

    continue stops the current iteration and jumps directly to the next one, without exiting the loop.

    Example: Process Only Even Numbers

    values = [1, 2, 3, 4, 5, 6]
    
    for v in values:
        if v % 2 != 0:
            continue  # skip odd numbers
        print("Even value:", v)
    
    # Output
    Even value: 2
    Even value: 4
    Even value: 6
    

    Explanation:

    Use continue when some items should be ignored but you still want the loop to run for the rest.


    Combining break and continue for Complex Patterns

    You can use both in the same loop to express more nuanced logic.

    Example: Validate User Inputs with Limits

    Imagine you allow the user up to 5 attempts to enter a valid positive integer. Negative numbers are ignored (skipped), and zero cancels the process entirely.

    attempts = 0
    max_attempts = 5
    
    while attempts < max_attempts:
        raw = input("Enter a positive integer (0 to cancel): ")
        attempts += 1
    
        if not raw.isdigit():
            print("Not a valid number, try again.")
            continue  # don't process further, go to next attempt
    
        value = int(raw)
    
        if value == 0:
            print("Cancelled by user.")
            break  # exit the loop completely
    
        if value < 0:
            # This case won't happen with isdigit(), but kept for illustration
            print("Negative values are ignored.")
            continue
    
        print("You entered:", value)
    
    print("Done.")
    
    # Example Output (one possible run)
    Enter a positive integer (0 to cancel): hello
    Not a valid number, try again.
    Enter a positive integer (0 to cancel): 42
    You entered: 42
    Enter a positive integer (0 to cancel): 0
    Cancelled by user.
    Done.
    

    Explanation:


    Using else with Loops

    Python allows an else block after a for or while loop. The else suite runs only if the loop ends normally, without hitting a break.

    Example: Search with for-else

    numbers = [4, 6, 9, 13]
    target = 10
    
    for n in numbers:
        if n == target:
            print("Found:", n)
            break
    else:
        print("Target not found in list.")
    
    # Output
    Target not found in list.
    

    Explanation:

    This is ideal for search tasks where you need to distinguish between:


    while-else with Early Termination

    The same concept applies to while loops.

    Example: Counting Down with a Condition

    count = 5
    
    while count > 0:
        print("Count:", count)
        if count == 2:
            print("Condition met, stopping early.")
            break
        count -= 1
    else:
        print("Countdown finished without early stop.")
    
    # Output
    Count: 5
    Count: 4
    Count: 3
    Count: 2
    Condition met, stopping early.
    

    Explanation:

    If you removed the if/break block, the loop would finish naturally and the else would run.


    Debugging and Predicting Loop Flow

    When break, continue, and else interact, tracing the flow is critical. A useful strategy is to add temporary debug prints.

    Example: Tracing a Loop with All Three

    items = ["ok", "skip", "ok", "stop", "ok"]
    
    for item in items:
        print("Start iteration with:", item)
    
        if item == "skip":
            print("  -> continue (skip processing)")
            continue
    
        if item == "stop":
            print("  -> break (exit loop)")
            break
    
        print("  -> processing", item)
    else:
        print("Loop completed without 'stop'.")
    
    # Output
    Start iteration with: ok
      -> processing ok
    Start iteration with: skip
      -> continue (skip processing)
    Start iteration with: ok
      -> processing ok
    Start iteration with: stop
      -> break (exit loop)
    

    Explanation:

    When debugging your own loops:


    Summary / Key Takeaways

    In this lesson on break, continue, and else with loops, you 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