Learn how to use the else clause with Python loops. Explore for and while else with examples, syntax, and practical use cases for better control flow understanding..
else
Clause in Loopsfor
loopwhile
loopIn Python, the else
clause can be used with loops (for
and while
). This may be surprising at first since most people associate else
with if
statements. However, in loops, the else
clause has a unique behavior:
else
block is executed only if the loop completes all its iterations without encountering a break
statement.break
, the else
block is skipped.The else
clause in loops (for
and while
) in Python is a bit unusual because most people associate else
with if
statements. In the context of loops, the else
clause is executed only when the loop finishes normally, meaning it wasn’t interrupted by a break
statement.
else
Clause in LoopsThe else
clause can be used with both for
and while
loops in Python. Here’s the general syntax:
for item in iterable:
# Code block to execute for each item
if condition:
break # Exit the loop early
else:
# Code block to execute if the loop completes without a break
while condition:
# Code block to execute while the condition is True
if condition_to_break:
break # Exit the loop early
else:
# Code block to execute if the loop completes without a break
How It Works:
for
loop:
else
block runs if the loop completes all its iterations without hitting a break
.break
, the else
block is skipped.while
loop:
else
block runs if the while
loop condition becomes False
naturally.break
, the else
block is skipped.for
loopLet’s say we’re searching for a specific number in a list.
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Number we want to find
target = 6
# Iterate over the list
for num in numbers:
if num == target:
print("Found the target!")
break
else:
print("Target not found in the list.")
Explanation:
target
.else
clause is skipped.break
), the else
block runs, printing “Target not found in the list.”
while
loop# Counter
i = 1
# Loop condition
while i <= 5:
if i == 3:
print("Breaking the loop")
break
print(i)
i += 1
else:
print("Loop finished without breaking.")
Explanation:
i
is less than or equal to 5.i
equals 3, the loop breaks.else
block is skipped.for
loop in Python is a programming statement that repeats a block of code a fixed number of times.
👉 Learn morewhile
loop in python is a control flow statement that repeatedly executes a block of code until a specified condition is met.
👉 Learn morematch-case
is a modern way to handle data-driven decision-making.
👉 Learn moreTutorials, Roadmaps, Bootcamps & Visualization Projects