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.
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 += 1Output: 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 += 1Output:
0
1
2
4Nested 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 rowOutput:
****
****
****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 rowOutput:
****
****
****Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
