Skip to main content

Command Palette

Search for a command to run...

Using else with Loops in Python 🐍

Published
1 min read
Using else with Loops in Python 🐍
A

👋 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!

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! 🎉

More from this blog

PythonChallenge

11 posts

Welcome to my Python blog, where I share my journey of learning and exploring the versatile world of Python programming! 🌟

Let’s code, learn, and grow together in the world of Python programming!