Fundamentals 4 min read

Python Basics: Using break, continue, and Nested Loops

This tutorial explains how break and continue control loop execution in Python, provides concrete while‑loop examples with their outputs, and demonstrates both for‑ and while‑based nested loops for printing multi‑row patterns, illustrating syntax and behavior step by step.

Lisa Notes
Lisa Notes
Lisa Notes
Python Basics: Using break, continue, and Nested Loops

Break and continue keywords

Both keywords are used inside Python loops. break terminates the entire loop, typically used to exit an infinite loop, while continue skips the current iteration and proceeds to the next one.

num = 0
while num < 5:
    if num == 3:
        num += 1
        break
    print(num)
    num += 1

Output: 0 1 2 When num == 3, the loop ends and the value 3 is not printed.

num = 0
while num < 5:
    if num == 3:
        num += 1
        continue
    print(num)
    num += 1

Output:

0
1
2
4

Nested loops

Python allows while and for loops to be nested, usually up to three levels. In a double loop, the outer loop controls rows and the inner loop controls the number of items per row.

Example: printing a 3‑row, 4‑column rectangle of asterisks using a for loop.

# for‑loop nested example
for i in range(0, 3):
    for j in range(0, 4):
        print("*", end="\t")
    print()  # newline after each row

Output:

****
****
****

Same pattern using a while loop.

i = 0
while i < 3:
    j = 0
    while j < 4:
        print("*", end=" ")
        j += 1
    i += 1
    print()  # newline after each row

Output:

****
****
****
Pythoncontinuefor loopwhile-loopnested loopsbreakloop control
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.