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

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • 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…

  • 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…

  • Decorators in Python

    Decorators in Python A decorator is a function that modifies the behavior of another function without permanently modifying it. Decorators are a powerful tool that use closure functions. Basic Concept A decorator: Simple Example python def simple_decorator(func): def wrapper(): print(“Something is happening before the function is called.”) func() print(“Something is happening after the function is…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

Leave a Reply

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