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

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • List of Basic Regular Expression Patterns in Python

    Complete List of Basic Regular Expression Patterns in Python Character Classes Pattern Description Example [abc] Matches any one of the characters a, b, or c [aeiou] matches any vowel [^abc] Matches any character except a, b, or c [^0-9] matches non-digits [a-z] Matches any character in range a to z [a-z] matches lowercase letters [A-Z] Matches any character in range…

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle Inheritance in OOP Python: Rectangle & Cuboid Example Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability ♻️ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is…

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

Leave a Reply

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