Loop Else in Python
Did you know loops in Python can have an else block? It’s a unique feature that surprises many new learners.
What is Loop Else?
In Python, both for and while loops can have an else clause.
The else block runs only if the loop finishes without being stopped by a break.
Syntax
for item in sequence:
# loop body
if condition:
break
else:
# runs if loop did NOT break
while condition:
# loop body
if condition_to_break:
break
else:
# runs if loop did NOT break
Example with For Loop
# Searching for a number
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n == 3:
print("Found 3!")
break
else:
print("3 not found")
Output: Found 3!
If you remove the break condition (e.g., search for 10), the loop ends normally and the else block executes:
for n in numbers:
if n == 10:
print("Found 10!")
break
else:
print("10 not found")
Output: 10 not found
Example with While Loop
i = 1
while i <= 5:
if i == 3:
print("Breaking at 3")
break
i += 1
else:
print("Loop finished without break")
Output: Breaking at 3
If you change the condition so it never breaks, the else part will run.
Common Mistakes
- Thinking Else Always Runs: It only runs if the loop completes naturally without
break. - Confusing with If-Else: The
elsehere belongs to the loop, not anifstatement. - Indentation Errors: Forgetting correct indentation can throw
IndentationError.
๐ก Real-Life Use Case
A very common use case is searching in a list:
names = ["Alice", "Bob", "Charlie"]
for name in names:
if name == "David":
print("Found David!")
break
else:
print("David not found")
This is cleaner than using a flag variable to track whether something was found.
๐ก Practice Challenges
- Search for a prime number in a list. If found, print it. If not, print “Not found”.
- Use a
whileloop withelseto simulate a countdown, and print “Blast off!” only if the countdown completes without interruption. - Search for a character in a string using a loop-else structure.
What’s Next?
With loop-else understood, we are now ready to dive deeper into functions in Python, where we learn to group code into reusable blocks.
No comments:
Post a Comment