Nested Loop Trace & Break/Continue Output Questions in Python

⚡ Direct Answer & Key Takeaway

In Python nested loops, the outer loop sets the row index while the inner loop completes all its iterations for every single outer step. Inside an inner loop, `break` exits only that innermost loop immediately (and skips its attached `else:` clause), whereas `continue` skips the remaining inner-loop statements and jumps straight to the next inner iteration. When `print(..., end=' ')` builds a pattern row, a trailing `print()` in the outer loop inserts each newline.

1. Row-by-Column Mechanics in Pattern Loops

Board pattern questions rely on coordinating two `range()` expressions so the inner variable depends on the outer variable. For a left-aligned triangle of `n` rows, the outer loop `for i in range(1, n + 1):` controls row numbers while `for j in range(1, i + 1):` controls how many items print on row `i`. Passing `end=' '` inside `print()` suppresses Python's default newline so inner iterations stay on the same line, and an empty `print()` placed at the outer indentation level moves the cursor down after each row finishes. When tracing inverted or character patterns using `chr(65 + j)`, construct a dry-run table listing `(i, j, output_buffer)` on paper. Checking the exact upper bound of `range(start, stop, step)`—remembering `stop` is always exclusive—prevents off-by-one errors on every pattern question.

  • Outer loop iterations determine total rows; inner loop iterations determine items per row.
  • Check `range(start, stop)` boundaries first—`stop` is never included in the sequence.
  • Track `print(..., end='')` and row-break `print()` indentation carefully during dry runs.

2. Scope of break and continue Inside Nested Loops

A common misconception in CBSE output prediction is assuming `break` terminates both loops at once. In Python, both `break` and `continue` strictly affect the nearest enclosing loop containing them. When an inner `for j` loop hits `break`, execution jumps out of the inner loop to the next statement inside the outer `for i` body, and the outer loop proceeds normally to `i + 1`. Meanwhile, `continue` inside the inner loop bypasses statements below it for the current `j` only, immediately advancing `j` to its next value—or ending the inner loop if `j` was on its final value. If you ever need to exit two loops simultaneously, wrap them in a function and `return`, or set a boolean flag tested by the outer loop.

  • `break` terminates only the innermost loop; the outer loop continues its remaining passes.
  • `continue` skips the rest of the current inner iteration without leaving the inner loop.
  • Use a boolean flag or function `return` when multi-level exit is required.

3. Tracing Loop-else Clauses and Edge Cases

CBSE Class 11 and 12 papers frequently include `for ... else:` inside nested loops, especially in prime-number or search-matrix snippets. Remember the golden rule: a loop's `else:` block runs if and only if the loop completes all iterations naturally without hitting `break`. Even if a loop executes zero times (such as `range(2, 2)` when checking `n = 2`), no `break` occurred, so the `else:` branch still executes! Conversely, hitting `continue` does not suppress the `else:` block because the loop still finishes normally. Always align indentation carefully on exam sheets: an `else:` aligned with the inner `for` belongs to the inner loop, whereas an `else:` aligned with `if` executes whenever the `if` condition evaluates to `False`.

  • Loop `else:` executes whenever the loop finishes without triggering `break`.
  • An empty `range()` triggers the `else:` clause immediately since no `break` ran.
  • Always match `else:` column indentation to distinguish loop-else from if-else.

4. Nested Loop Pattern with continue and Prime Search Using Inner for-else

# Part A: Number triangle with continue skipping multiples of 2
for i in range(1, 5):
    for j in range(1, i + 1):
        if j % 2 == 0:
            continue
        print(j, end="")
    print()

# Part B: Nested break + inner for-else trace (primes between 2 and 7)
primes = []
for num in range(2, 8):
    for div in range(2, num):
        if num % div == 0:
            break
    else:
        primes.append(num)
print("Primes:", primes)

Verified Console / Dry-Run Output:

1
1
13
13
Primes: [2, 3, 5, 7]

5. Control Flow Rules for Nested Loops, break, continue, and else

Statement / ConstructScope AffectedLoop else: Triggered?Next Execution Point
break inside inner loopInner loop onlyNo (skipped)First statement after inner loop inside outer body
continue inside inner loopCurrent inner iteration onlyYes (if loop completes later)Next value of inner loop variable
Inner loop ends normallyInner loop completeYesLoop else: block (if present), else outer body
print() in outer bodyAfter inner loop finishesN/AOutputs newline before next outer row starts
🎯 1-on-1 Live Mentorship & Free Study Kit

Practice CBSE Output Tracing 1-on-1 with 4Achievers Junior

Master dry-run tables and loop-control output questions for CBSE CS (083) with 4Achievers Junior (Grades 3-12) in 1-on-1 or 1:4 Micro-Pods.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Assuming `break` inside the inner loop exits the outer loop as well; it only exits the loop immediately enclosing it.
  • Avoid Mistake: Placing the row-ending `print()` inside the inner loop instead of aligned with the inner `for`, printing one value per line.
  • Avoid Mistake: Thinking `continue` cancels a loop's `else:` clause; only `break` skips the `else:` block.
  • Avoid Mistake: Miscounting `range(1, 5)` as running through `5` instead of stopping at `4`.
  • Examiner / Mentor Tip: Always draw a neat dry-run table with columns for outer variable, inner variable, condition result, and printed line.
  • Examiner / Mentor Tip: Pay close attention to `end=''` vs `end=' '` vs default newline when writing exact output on board answer sheets.
  • Examiner / Mentor Tip: When `continue` triggers on the last inner iteration, the inner loop exits cleanly and still runs any attached `else:` block.

7. Interactive Concept Check Quiz

Question: What is printed by: `for i in range(2):` / `for j in range(3):` / `if j == 1: continue` / `if j == 2: break` / `print(f'{i}-{j}', end=' ')`?

8. Frequently Asked Questions

How do I break out of both outer and inner loops at once in Python?
Python has no labeled `break`. Either wrap the nested loops in a helper function and use `return`, or set a boolean flag before breaking the inner loop and check that flag in the outer loop.
If an inner loop runs zero iterations, is its else block skipped?
No. The `else:` block runs even when the loop runs zero times (for example `range(2, 2)` when `num = 2`), because no `break` was executed.
How can I quickly tell whether else belongs to if or for in an exam snippet?
Check the indentation level: an `else:` aligned under `for` runs when the loop finishes without `break`, whereas an `else:` aligned under `if` runs whenever that `if` condition is False.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class