Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Loops: while, for, break, continue and pass

Python loop control: while, for over iterables/range, and the control statements break, continue, pass, including loop-else, syntax, flow, and pitfalls.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers repeat operations many times: reading sensor data until a threshold, iterating over files, simulating time steps, or processing records in a dataset. Loops let you write this once and run it many times safely and efficiently. Knowing when to use while vs for, and how break, continue and pass control execution, is essential for correct, readable, and efficient programs.

Key ideas

  • Definition — Entry-controlled loop: A loop where the continuation condition is checked before each iteration. In Python, both while and for are entry-controlled: execution enters the body only if the condition (while) is True or if there is a next item (for).
  • Definition — Loop control variable: A variable that determines the progress of the loop, such as a counter in while or the target in for (e.g., i in for i in range(...)).
  • Definition — Infinite loop: A loop that never terminates because its stopping condition is never reached or never becomes false.
  • Definition — Iterable: Any Python object capable of returning its members one at a time, such as list, tuple, set, dict, string, range, file, and many more.
  • Definition — Iterator: An object with a state that remembers the current position in the iteration and provides the next value when requested.

Exact statements useful for exams:

  1. Definition — while statement semantics: The while statement repeatedly executes its body as long as its condition evaluates to True. On each iteration: (a) evaluate the condition; (b) if True, execute the body; (c) repeat; if False, exit the loop and proceed to the next statement after the loop (or to the optional else block if present and no break occurred).
  2. Definition — for statement semantics: The for statement iterates over items of an iterable in its iteration order (not necessarily sorted; sets are unordered, and dicts iterate keys in insertion order in Python 3.7+). On each iteration: (a) request the next item from the iterable; (b) if an item exists, assign it to the target variable(s) and execute the body; (c) if no item remains, exit the loop and proceed to the next statement after the loop (or to the optional else block if present and no break occurred).
  3. Definition — break: The break statement immediately terminates the nearest enclosing loop and transfers control to the statement following the loop. It does not terminate outer loops.
  4. Definition — continue: The continue statement skips the remaining statements in the current iteration and moves control to the next iteration (re-checking the condition for while, or fetching the next item for for).
  5. Definition — pass: The pass statement does nothing. It acts as a placeholder where a statement is syntactically required but no action is needed yet.
  6. Definition — loop-else clause: A loop may have an optional else block. The else block executes only if the loop terminates normally (i.e., the while condition becomes False or the for iterable is exhausted) and not via break. It also does not execute if the loop exits via return or an exception.

Assumptions and prerequisites:

  • Indentation is syntactically significant in Python. A consistent indent (commonly 4 spaces) defines the loop body.
  • Boolean expressions (from the Decision control statements topic) are used in while conditions.
  • Collections and iterables (from Lists and tuples; Sets and dictionaries; Strings and string methods) are commonly used with for.

Derivation-style explanations (typical exam development):

  • Flow of a while loop (describe a diagram): Draw a flowchart with these elements top to bottom: (1) Start (oval), (2) Condition (diamond) labeled “condition?”; True arrow leads to (3) Body (rectangle) labeled with body statements; then an arrow loops back to the condition. The False arrow from the condition goes to (4) Else block (optional, rectangle) labeled “else body” and then to (5) Next statement (oval). Label arrows “True” and “False”. If else is absent, the False arrow goes directly to Next statement.
  • Flow of a for loop: Draw a flowchart: (1) Start; (2) Get iterator from iterable (parallelogram); (3) Next item? (diamond). True arrow to (4) Assign to target and execute body (rectangle), then back to (3). False arrow to (5) Else block (optional, rectangle) and then (6) Next statement.
  • Placement of break and continue in flow: In the body rectangle, show two internal diamonds: “break?” leading directly to Next statement (skipping else), and “continue?” leading back to Condition/Next item without executing remaining body statements.

Choosing the right loop:

  • Use while when you do not know in advance how many iterations are needed, but you know the stopping condition (e.g., read until empty, simulate until error < tolerance).
  • Use for when iterating over a known collection, a sequence of numbers, or any iterable (e.g., for each element, for i in range(n)).

Loop correctness pointers:

  • Maintain a clear invariant: a statement that is true before the loop and remains true after each iteration (useful in reasoning and proofs of correctness).
  • Ensure progress: each iteration should move towards termination (e.g., decrement a counter, advance an index, consume input).

Formulas

For this programming topic, remember these syntax patterns:

  • while condition:
  • while True: # indefinite loop; exit with break
  • for target in iterable:
  • break
  • continue
  • pass
  • while condition: body else: else_body
  • for target in iterable: body else: else_body
  • for i in range(stop):
  • for i in range(start, stop):
  • for i in range(start, stop, step):
  • Multiple assignment in for: for a, b in iterable_of_pairs:
  • for idx, val in enumerate(seq): to iterate with indices and values
  • for key, val in dict_obj.items(): to iterate key–value pairs
  • Nested loops: for i in A: for j in B: ...

Key notes:

  • Indentation defines the loop body.
  • range(n) generates integers 0 to n−1.
  • range(start, stop, step) excludes stop and uses step increments (can be negative). Step cannot be 0 (raises ValueError).
  • for ch in "abc": iterates characters 'a', 'b', 'c'.
  • for key in dict_obj: iterates keys by default.

Worked examples

Example 1 — While loop with running sum and continue (reads N numbers and sums only positives) Complete program:

# Read N and then N integers; sum only the positive numbers
N = int(input().strip())

total = 0
count = 0
while count < N:
    x = int(input().strip())
    count += 1
    if x <= 0:
        continue  # skip non-positive values
    total += x

print(total)

Sample input:

5
3
-2
0
7
4

Exact output:

14

Explanation: Among 3, -2, 0, 7, 4 only positives are 3, 7, 4; sum = 14. The continue prevents adding non-positive values but still counts the inputs, avoiding an infinite loop.

Example 2 — For loop with break and loop-else (search for a target in a list) Complete program:

# Read a space-separated list, then a target; report if found using for-else
arr = input().strip().split()
target = input().strip()

for item in arr:
    if item == target:
        print("Found")
        break
else:
    print("Not found")

Sample input:

apple banana mango guava
mango

Exact output:

Found

If the target is absent, e.g., input:

apple banana mango guava
lychee

Exact output:

Not found

Explanation: The else runs only if the loop finishes without break. When item == target, break prevents the else from running.

Example 3 — Nested loops with range and pass (multiplication table, skipping a diagonal using continue) Complete program:

# Print a 1..n multiplication table but skip i==j products; use pass as a placeholder
n = int(input().strip())

if n <= 0:
    pass  # nothing to do for non-positive n
else:
    for i in range(1, n + 1):
        row = []
        for j in range(1, n + 1):
            if i == j:
                continue  # skip diagonal entries
            row.append(str(i * j))
        print(" ".join(row))

Sample input:

3

Exact output:

2 3
2 6
3 6

Explanation: For n = 3, the products for (i, j) pairs except (1,1), (2,2), (3,3) are printed row-wise. The pass here is a no-op placeholder for the invalid n case.

Example 4 — While-else for primality test (simple, clear logic) Complete program:

# Check if an integer >= 2 is prime using while-else
n = int(input().strip())

if n < 2:
    print("Not prime")
else:
    d = 2
    while d * d <= n:
        if n % d == 0:
            print("Not prime")
            break
        d += 1
    else:
        print("Prime")

Sample input:

29

Exact output:

Prime

Explanation: The loop searches for a divisor d up to sqrt(n). If none is found (no break), the else prints "Prime".

Common mistakes

  • Expecting for to iterate indices by default: In Python, for x in list iterates items, not indices. Use enumerate(list) for index and value, or range(len(list)) if indices are required.
  • Confusing loop-else semantics: Thinking else always runs if the condition is False at the start. In loops, else runs only when the loop exits without break; continue does not affect else.
  • Modifying a list while iterating over it: Removing/appending elements to the list being iterated can skip items or repeat items. Iterate over a copy (list_name[:]) or build a new list.
  • Using pass where a statement is required to act: Remember pass does nothing; it is only a placeholder. It does not skip iterations or print output.
  • Indentation and colon errors: Missing : after while or for, or inconsistent indentation causing SyntaxError or unintended block grouping.
  • Using == True in while conditions unnecessarily: Prefer while condition: e.g., while flag: instead of while flag == True:.
  • Heavy computation inside Python loops over large arrays: For performance, consider vectorized operations using libraries (covered under Modules, packages and the standard library) or list comprehensions when suitable.

For your exam

Typical question types and what a full-marks answer includes:

  • Definitions (short answers): Define while loop, for loop, break, continue, pass, iterable, iterator, loop-else. Include a one-line semantics statement and a minimal syntax example.
  • Short notes: Compare while and for (when to use, entry-controlled nature, examples). Include a labeled flow description for each with True/False branches, and note on else behavior.
  • Trace the output: Given a code snippet with nested loops, determine the exact output step by step. Show the iteration variable values each step and where break/continue trigger.
  • Write programs: (a) Sum of digits using while. (b) Search an element using for-else. (c) Generate a pattern (e.g., star pyramid) using nested for loops. Provide complete, runnable code and sample I/O.
  • Error finding: Identify logical errors (infinite loop, off-by-one in range, misplaced break) and correct them with an explanation.
  • Concept application: Explain loop-else with an example; state precisely when else runs and when it does not, including with continue and with break inside nested loops.
  • Diagram/flowchart: Draw the while loop flow with condition check before body, and indicate where break and continue divert control. Label all arrows and blocks.

Exam presentation tips:

  • Write syntax exactly with colons and proper indentation in code answers.
  • For loop-else, explicitly state: "Else executes only if no break occurs in the loop."
  • For range, state clearly that stop is excluded and step can be negative.
  • When tracing, list iteration variables and outputs line by line to avoid mistakes.

Quick check

  1. State the difference between break and continue in one line each.
  2. What does the else clause of a for loop do, and when does it execute?
  3. Write a one-line Python for loop to print squares of numbers 1 to 5 inclusive.

Answers: 1) break exits the nearest loop immediately; continue skips the rest of the current iteration and proceeds to the next. 2) The loop’s else block runs only if the loop finishes normally without a break (i.e., condition becomes False for while or iterable is exhausted for for). 3) for i in range(1, 6): print(i*i)

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?