Using else with Loops in Python π
In Python, you can use an else
block with both for
and while
loops. But hereβs the catch: the else
block will only execute if the loop completes successfully without encountering a break
.
Example with for
Loop:
pythonCopy codenumbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break # Exits the loop when it encounters 3
print(num)
else:
print("Loop completed successfully")
Output:
Copy code1
2
In this case, the loop exits early due to the break
, so the else
block is not executed.
When else
Runs:
The else
block runs when the loop finishes without a break
:
pythonCopy codenumbers = [1, 2, 4, 5]
for num in numbers:
print(num)
else:
print("Loop completed successfully")
Output:
vbnetCopy code1
2
4
5
Loop completed successfully
The same behavior applies to while
loops. Use else
to run code after a successful loop execution! π
Subscribe to my newsletter
Read articles from Aakanchha Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Aakanchha Sharma
Aakanchha Sharma
π Welcome to my Hashnode blog! I'm a tech enthusiast and cloud advocate with expertise in IT, backup solutions, and cloud technologies. Currently, Iβm diving deep into Python and exploring its applications in automation and data management. I share insights, tutorials, and tips on all things tech, aiming to help fellow developers and enthusiasts. Join me on this journey of learning and innovation!