Nested for loops, break, continue, and pass in for loops

break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop.

1. break Statement

The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop.

Example:

Python

print("--- Using 'break' ---")
for i in range(1, 6):
    if i == 3:
        print(f"Breaking loop at i = {i}")
        break  # Exit the loop when i is 3
    print(f"Current value: {i}")
print("Loop finished (due to break).")

Output:

--- Using 'break' ---
Current value: 1
Current value: 2
Breaking loop at i = 3
Loop finished (due to break).

Explanation: The loop starts, and i prints 1 and 2. When i becomes 3, the if condition is true, break is executed, and the loop terminates. The print(f"Current value: {i}") for i=3 and subsequent values is never reached.

2. continue Statement

The continue statement is used to skip the rest of the current iteration of the loop and move to the next iteration. The loop does not terminate; it just bypasses the remaining code within the current iteration.

Example:

Python

print("\n--- Using 'continue' ---")
for i in range(1, 6):
    if i == 3:
        print(f"Skipping iteration for i = {i}")
        continue  # Skip the rest of this iteration when i is 3
    print(f"Current value: {i}")
print("Loop finished (after continue).")

Output:

--- Using 'continue' ---
Current value: 1
Current value: 2
Skipping iteration for i = 3
Current value: 4
Current value: 5
Loop finished (after continue).

Explanation: When i is 3, the if condition is true, continue is executed. This causes the print(f"Current value: {i}") line to be skipped for i=3, and the loop immediately proceeds to the next iteration (where i becomes 4).

3. pass Statement

The pass statement is a null operation; nothing happens when it is executed. It is primarily used as a placeholder when a statement is syntactically required but you don’t want any code to execute. It’s useful when you’re defining a loop or function but haven’t decided on its implementation yet, or when you want to catch an error but do nothing about it.

Example:

Python

print("\n--- Using 'pass' ---")
for i in range(1, 6):
    if i % 2 == 0:
        pass  # Do nothing if i is even
        print(f"Just passed for even number: {i}") # This line still executes after pass
    else:
        print(f"Odd number: {i}")
print("Loop finished (with pass).")

Output:

--- Using 'pass' ---
Odd number: 1
Just passed for even number: 2
Odd number: 3
Just passed for even number: 4
Odd number: 5
Loop finished (with pass).

Explanation: When i is even, pass is executed. It literally does nothing, and the execution simply continues to the next line of code within the if block (print(f"Just passed for even number: {i}")). It doesn’t skip the rest of the iteration (like continue) or terminate the loop (like break). It just fulfills the syntax requirement.

When to use pass:

  • Placeholder for future code: If you’re outlining your code structure and need a loop or function that will be implemented later.Pythondef my_future_function(): pass # To be implemented later
  • Minimalistic exception handling:Pythontry: # some code that might raise an error result = 10 / 0 except ZeroDivisionError: pass # Ignore the error for now, or log it without crashing

In summary:

  • break: Exits the loop completely.
  • continue: Skips the current iteration and moves to the next.
  • pass: Does nothing; it’s a placeholder.

Nested for loops

Let’s explore nested for loops in Python with a simple example. A nested for loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.

Imagine you’re trying to print a multiplication table or iterate through rows and columns of a grid. This is where nested loops come in handy.

Basic Concept

The general structure looks like this:

Python

for outer_variable in outer_sequence:
    # Code executed for each item in outer_sequence
    for inner_variable in inner_sequence:
        # Code executed for each item in inner_sequence,
        # for *each* iteration of the outer loop
        # ...

Simple Example: Printing a 2D Grid or Coordinates

Let’s say you want to print out all possible combinations of numbers from 0 to 2 for both an ‘outer’ and an ‘inner’ loop, representing coordinates (x, y).

Python

print("--- Nested For Loop Example ---")

# Outer loop iterates from 0 to 2 (x-coordinate)
for x in range(3):
    print(f"Outer loop iteration: x = {x}")
    # Inner loop iterates from 0 to 2 (y-coordinate) for each 'x'
    for y in range(3):
        print(f"    Inner loop iteration: y = {y} (Current coordinate: ({x}, {y}))")
    print("-" * 30) # Separator for clarity after each outer loop iteration

print("--- Nested For Loop Finished ---")

Output:

--- Nested For Loop Example ---
Outer loop iteration: x = 0
    Inner loop iteration: y = 0 (Current coordinate: (0, 0))
    Inner loop iteration: y = 1 (Current coordinate: (0, 1))
    Inner loop iteration: y = 2 (Current coordinate: (0, 2))
------------------------------
Outer loop iteration: x = 1
    Inner loop iteration: y = 0 (Current coordinate: (1, 0))
    Inner loop iteration: y = 1 (Current coordinate: (1, 1))
    Inner loop iteration: y = 2 (Current coordinate: (1, 2))
------------------------------
Outer loop iteration: x = 2
    Inner loop iteration: y = 0 (Current coordinate: (2, 0))
    Inner loop iteration: y = 1 (Current coordinate: (2, 1))
    Inner loop iteration: y = 2 (Current coordinate: (2, 2))
------------------------------
--- Nested For Loop Finished ---

Explanation of the Flow:

  1. Outer Loop (for x in range(3)):
    • Starts with x = 0.
    • The code inside the outer loop begins execution.
    • Inner Loop (for y in range(3)):
      • For x = 0, the inner loop runs completely:
        • y = 0 (prints (0, 0))
        • y = 1 (prints (0, 1))
        • y = 2 (prints (0, 2))
    • After the inner loop finishes, the print("-" * 30) is executed.
    • The outer loop moves to its next iteration.
  2. Outer Loop (for x in range(3)):
    • Now x = 1.
    • The code inside the outer loop begins execution again.
    • Inner Loop (for y in range(3)):
      • For x = 1, the inner loop runs completely again:
        • y = 0 (prints (1, 0))
        • y = 1 (prints (1, 1))
        • y = 2 (prints (1, 2))
    • After the inner loop finishes, the print("-" * 30) is executed.
    • The outer loop moves to its next iteration.
  3. Outer Loop (for x in range(3)):
    • Now x = 2.
    • The process repeats for x = 2, with the inner loop running for y = 0, 1, 2.
    • After the inner loop finishes, the print("-" * 30) is executed.
    • The outer loop has no more iterations, so the entire nested loop structure finishes.

Another Common Use Case: Multiplication Table

Python

print("\n--- Multiplication Table (1-5) ---")

for i in range(1, 6):  # Outer loop for numbers 1 to 5
    for j in range(1, 6):  # Inner loop for multipliers 1 to 5
        # Using end=" " to print on the same line, and then a newline after each row
        print(f"{i * j:4}", end=" ") # :4 for formatting to take 4 spaces
    print() # Newline after each row of the table

print("--- Table Finished ---")

Output:

--- Multiplication Table (1-5) ---
   1    2    3    4    5 
   2    4    6    8   10 
   3    6    9   12   15 
   4    8   12   16   20 
   5   10   15   20   25 
--- Table Finished ---

This example clearly shows how the inner loop completes all its iterations for each iteration of the outer loop, resulting in a structured output like a table.

Similar Posts

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • Top Python IDEs in 2025: Best Tools for Developers , Data Scientists, Beginners, Professionals

    Python developers have a wide range of Integrated Development Environments (IDEs) to choose from, depending on their needs, preferences, and the type of projects they are working on. Below is a list of popular IDEs for Python, along with their key features: 1. PyCharm 2. Visual Studio Code (VS Code) 3. Jupyter Notebook/JupyterLab 4. Spyder…

  • re.fullmatch() Method

    Python re.fullmatch() Method Explained The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t. Syntax python re.fullmatch(pattern, string, flags=0) import re # Target string string = “The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by…

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

Leave a Reply

Your email address will not be published. Required fields are marked *