For-Else: A Weird but Useful Feature in Python

Use it properly and skilfully

Yang Zhou
TechToFreedom

--

No matter which programming language we use, we all write “if-else” statements, but how about “for-else” ?

For many languages, such as C, C++ and Java, it’s totally wrong if you use an “else” after a loop. However, Python, as an elegant language, has this weird but useful feature. If we use it properly, our code will become neater and cleaner.

This article will introduce the “for-else” feature in Python and explain how to use it properly by simple examples.

The Basics of the “For-Else” Feature

The “for-else” feature looks strange and hard to understand when a Python developer encounters it for the first time. But in fact, its usage is unexpectedly simple. One sentence is enough to explain it:

The “else” block only executes when there is no break in the loop.

Too simple to be true? Let’s check it out by an example:

--

--