What happens if the break statement is used inside a nested loop?

What happens if the break statement is used inside a nested loop?

a) It breaks out of all loops
b) It only breaks out of the innermost loop
c) It continues the outer loop
d) It causes an error

Answer:

b) It only breaks out of the innermost loop

Explanation:

When the break statement is used inside a nested loop in Python, it only terminates the innermost loop in which it is placed. The outer loops continue to execute as normal unless they also contain a break statement.

for i in range(3):
    for j in range(5):
        if j == 2:
            break  # Breaks out of the inner loop
        print(i, j)  # Prints pairs of (i, j) until j equals 2

In this example, the break statement exits the inner loop when j equals 2, but the outer loop continues its next iteration. Understanding how break works in nested loops is essential for controlling complex loop structures effectively.

Leave a Comment

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

Scroll to Top