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

  • ASCII ,Uni Code Related Functions in Python

    ASCII Code and Related Functions in Python ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns numerical values to letters, digits, punctuation marks, and other characters. Here’s an explanation of ASCII and Python functions that work with it. ASCII Basics Python Functions for ASCII 1. ord() – Get ASCII value of a…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

  • Anchors (Position Matchers)

    Anchors (Position Matchers) in Python Regular Expressions – Detailed Explanation Basic Anchors 1. ^ – Start of String/Line Anchor Description: Matches the start of a string, or start of any line when re.MULTILINE flag is used Example 1: Match at start of string python import re text = “Python is great\nPython is powerful” result = re.findall(r’^Python’, text) print(result) #…

  • Functions as Parameters in Python

    Functions as Parameters in Python In Python, functions are first-class objects, which means they can be: Basic Concept When we pass a function as a parameter, we’re essentially allowing one function to use another function’s behavior. Simple Examples Example 1: Basic Function as Parameter python def greet(name): return f”Hello, {name}!” def farewell(name): return f”Goodbye, {name}!” def…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

Leave a Reply

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