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

  • Python and PyCharm Installation on Windows: Complete Beginner’s Guide 2025

    Installing Python and PyCharm on Windows is a straightforward process. Below are the prerequisites and step-by-step instructions for installation. Prerequisites for Installing Python and PyCharm on Windows Step-by-Step Guide to Install Python on Windows Step 1: Download Python Step 2: Run the Python Installer Step 3: Verify Python Installation If Python is installed correctly, it…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

  • Object: Methods and properties

    🚗 Car Properties ⚙️ Car Methods 🚗 Car Properties Properties are the nouns that describe a car. They are the characteristics or attributes that define a specific car’s state. Think of them as the data associated with a car object. Examples: ⚙️ Car Methods Methods are the verbs that describe what a car can do….

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • re.I, re.S, re.X

    Python re Flags: re.I, re.S, re.X Explained Flags modify how regular expressions work. They’re used as optional parameters in re functions like re.search(), re.findall(), etc. 1. re.I or re.IGNORECASE Purpose: Makes the pattern matching case-insensitive Without re.I (Case-sensitive): python import re text = “Hello WORLD hello World” # Case-sensitive search matches = re.findall(r’hello’, text) print(“Case-sensitive:”, matches) # Output: [‘hello’] # Only finds lowercase…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

Leave a Reply

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