VMware ESXi and vSphere Cluster Management

Nested Loop Statements in Python

Learn how Python nested loops work, including outer and inner loops, execution order, range() boundaries, sentinel-controlled input, and practical examples.

A nested loop is a loop placed inside the body of another loop. The surrounding loop is the outer loop, and the loop inside it is the inner loop. Python supports many combinations, including while inside while, for inside for, for inside while, and while inside for.

Nested loops are useful when one task must be repeated for every value or iteration controlled by another task. Common examples include generating rows and columns, processing lists of lists, creating multiplication tables, producing coordinate pairs, and repeating a task for each user entry.

This lesson assumes that you know variables, assignment, input(), integer conversion with int(), Boolean comparisons, while loops, for loops, and range().

How nested loops execute

A while loop continues while its Boolean condition is true. A for loop takes items from an iterable, such as the sequence of integers produced by range(). One execution cycle of a loop is called an iteration.

When the outer loop begins one iteration, Python enters its body. If that body contains an inner loop, Python runs the inner loop completely before returning to the outer loop. Only after the inner loop has finished does the outer loop move to its next iteration.

for outer_value in range(3):
    print("Outer:", outer_value)
    for inner_value in range(2):
        print("  Inner:", inner_value)
    print("Inner loop finished")

The execution order is:

  1. The outer loop produces 0.
  2. The inner loop produces 0 and then 1.
  3. The statement after the inner loop runs.
  4. The outer loop produces 1, and the entire inner loop starts again.
  5. The same process occurs for outer value 2.
Outer-loop valueInner-loop values producedOutputNext outer-loop action
00, 1Outer 0, then Inner 0 and Inner 1Advance to outer value 1
10, 1Outer 1, then Inner 0 and Inner 1Advance to outer value 2
20, 1Outer 2, then Inner 0 and Inner 1Stop after the outer range ends

Indentation defines the loop structure

Indentation is the leading whitespace that defines code blocks in Python. The inner loop must be indented inside the outer loop. Statements belonging to the inner loop are indented one additional level. A statement placed after the inner loop but aligned with the inner-loop header remains inside the outer loop while running outside the inner loop.

while outer_condition:
    for item in iterable:
        # This is inside both loops.
        inner_work(item)
    # This is inside the outer loop but outside the inner loop.
    outer_work()

Incorrect indentation can cause an IndentationError, or it can change when a statement runs. For example, placing the next input statement inside the for loop would request input once per inner iteration rather than once per outer iteration.

Nested while and for loops with a sentinel

A sentinel value is a special value that signals that repetition should stop. In this example, 0 is the sentinel. The outer while loop checks whether the current input is not zero. For every nonzero input, the inner for loop prints the positive integers less than that input.

value = int(input("Enter a number (0 to stop): "))

while value != 0:
    for number in range(1, value):
        print(number)

    value = int(input("Enter a number (0 to stop): "))

Here, value controls the outer loop. It is the outer-loop control value. The variable number belongs to the inner for loop and receives successive values from range(1, value).

The second input statement is important. It is inside the outer loop but outside the inner loop, so a new value is obtained after the inner loop completes. Without this update, value would remain unchanged and a nonzero entry could make the program repeat forever.

If the user enters 0, the condition value != 0 is false. The outer loop body, including the inner loop, is skipped. Therefore, the terminating value does not trigger number printing.

Example execution

If the inputs are 5, 12, and then 0, the program behaves as follows:

  • For 5, the inner loop prints 1, 2, 3, and 4.
  • After the inner loop finishes, the program prompts again.
  • For 12, it prints 1 through 11.
  • After the next prompt receives 0, the outer condition becomes false and the program ends.

Understanding range(1, x)

range() produces integers for a for loop. With two arguments, range(start, stop) begins at start and stops before stop. The ending value is exclusive.

Therefore, range(1, x) begins at 1 and produces positive integers less than x. When x is 5, it produces 1, 2, 3, and 4, not 5. This boundary behavior can cause an off-by-one result when the intended endpoint is misunderstood.

Value of xValues generated by range(1, x)Explanation
51, 2, 3, 4Starts at 1 and stops before 5.
1No valuesThe start and stop are equal, so the range is empty.
0No valuesThe stop value is less than the starting bound.
-3No valuesThe stop value is less than the starting bound.
31, 2Only values strictly less than 3 are generated.

For an input of zero, the outer loop does not run at all because zero is the sentinel. For a negative number or a number less than or equal to 1, the outer loop may run, but range(1, x) is empty and the inner body executes zero times. If the program should reject such values, validate the input explicitly.

If the intended output includes the entered value, use range(1, x + 1) instead:

for number in range(1, x + 1):
    print(number)

Loop variables and updates

The outer and inner loops can use different variables because they represent different responsibilities. In the sentinel example, value determines whether the outer loop continues and determines the inner range. The inner variable number represents one generated integer at a time.

A for-loop variable is automatically assigned each successive value from its iterable:

for number in range(1, 5):
    print(number)

There is usually no need to write number += 1 inside this loop. Manually changing number does not alter the values that range() will generate. On the next iteration, the for loop assigns the next value from the range. Manual updates can also make the code confusing.

A while loop is different: its condition depends on values that your code must update. In the sentinel example, the next call to input() changes value so that the loop condition can eventually become false.

Other combinations of nested loops

For loop inside a for loop: a multiplication table

The outer loop can represent table rows, while the inner loop represents the multiplication values in each row.

for row in range(1, 4):
    for multiplier in range(1, 6):
        print(row * multiplier, end=" ")
    print()

The inner loop runs five times for each row. After it finishes, print() moves to the next output line, and the outer loop starts the next row.

For loops for coordinate pairs

Nested loops can generate every combination of an outer value and an inner value:

for x in range(2):
    for y in range(3):
        print((x, y))

The output contains (0, 0), (0, 1), (0, 2), followed by (1, 0), (1, 1), and (1, 2). Each x value is paired with every y value.

While loop inside a for loop

The loop types do not have to match. For example, a for loop can select groups while a while loop processes items within each group:

for group in range(2):
    item = 0
    while item < 3:
        print(group, item)
        item += 1

The inner while loop must update item; otherwise its condition may remain true indefinitely.

Common uses of nested loops

  • Rows and columns: Generate formatted grids, tables, or repeated visual patterns.
  • Two-dimensional data: Visit each item in a list of lists by using one loop for rows and another for items in each row.
  • Multiplication tables: Use one loop for each table or row and another for each multiplier.
  • Coordinate pairs: Generate every combination of positions or options.
  • Grouped work: Repeat an inner task for every user entry, file group, category, or data set.

Efficiency and readability

Nested loops can multiply the number of operations. If an outer loop runs m times and the inner loop runs n times for each outer iteration, the inner body can run up to m × n times. For example, a 100-iteration outer loop with a 100-iteration inner loop can execute the inner body 10,000 times.

  • Use meaningful names such as row, column, group, and item.
  • Keep each loop body simple and place reusable work in a function when appropriate.
  • Check whether a simpler structure, a direct operation, or a comprehension can solve the problem without unnecessary nesting.
  • Measure or reason about the amount of work when loop ranges may become large.

Troubleshooting nested loops

The program never stops

The outer-loop control value may not be updated inside the while loop. Request a new value during every outer iteration, or otherwise change the value used by the loop condition.

The entered number is not printed

range(1, x) excludes x. Use range(1, x + 1) when the desired output includes the entered number.

Indentation errors or unexpected execution order

Indent the inner loop beneath the outer loop, its body one level further, and post-inner-loop statements so they align with the inner-loop header. The next input statement should be inside the outer loop but outside the inner loop.

Changing the inner loop variable does not help

A for loop controls its variable by assigning values from its iterable. Remove a manual increment unless it serves a separate purpose; let range() provide the sequence.

No values print for a negative number or for 1

range(1, x) has no values when x is less than or equal to the starting bound of 1. Validate the input or define the expected behavior for these cases.

Text input causes a conversion error

int() cannot convert arbitrary text. If invalid entries must be handled, use input validation with try and except:

try:
    value = int(input("Enter a number: "))
except ValueError:
    print("Please enter an integer.")

Summary

  • A nested loop is a loop inside another loop.
  • The outer loop controls when the inner loop is repeated.
  • The inner loop normally runs to completion during each outer-loop iteration.
  • Indentation determines whether code belongs to the outer loop, inner loop, or both.
  • range(1, x) includes 1 but excludes x.
  • A sentinel such as zero can stop a while loop before its inner loop runs.
  • A for-loop variable is assigned automatically, so manually incrementing it is usually unnecessary.
  • Nested loops are powerful, but their operation count can grow quickly, so keep them readable and avoid unnecessary nesting.

See also: Nested Loop Statements.