“Else” condition inside a “for” loop

Despite all the Python code that you have seen so far, chances are that you may have missed the following “for-else” which I also got to see for the first time a couple of weeks ago.

This is a “for-else” method of looping through a list, where despite having an iteration through a list, you also have an “else” condition, which is quite unusual.

This is not something that I have seen in other programming languages like Java, Ruby, or JavaScript.

Let’s see an example of how it looks in practice.

Let’s say that we are trying to check whether there are no odd numbers in a list.

Let’s iterate through it:

numbers = [2, 4, 6, 8, 1]

for number in numbers:
    if number % 2 == 1:
        print(number)
        break
else:
    print("No odd numbers")

In case we find an odd number, then that number will be printed since break will be executed and the else branch will be skipped.

Otherwise, if break is never executed, the execution flow will continue with the else branch.

In this example, we are going to print 1.