Understand Python for-else: A Beginner Guide – Python Tutorial

By | September 2, 2020

You may find for-else in some python codes. In this tutorial, we will use some examples to show you how to use it.

Syntax

for-else is defined as:

for condition:
    for_body
else:
    else_body

Python for statement is easy to understand. We should know when to run else_body.

If for loop ends normally, it is not terminated by break. else_body will be run.

We will use some examples to show you this point.

Example 1.

search='apple'
fruits = ['apple', 'banana', 'mango']

for fruit in fruits:
    if search == fruit:
        print("fruit is found")
        break
else:
    print("no fruit found")

Run this code, you will get:

fruit is found

Why?

Because for statement is terminated by break, which means else statement can not be run.

However, if we remove break statement.

search='apple'
fruits = ['apple', 'banana', 'mango']

for fruit in fruits:
    if search == fruit:
        print("fruit is found")
else:
    print("no fruit found")

Run this code, you will get:

fruit is found
no fruit found

Because for statement ends normally, else statement is run.

Example 2.

Look at this example:

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print( n, 'equals', x, '*', n/x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

As to else statement, we can find it will be run when n = 2, 3, 5, 7.

The result is:

2 is a prime number
3 is a prime number
4 equals 2 * 2.0
5 is a prime number
6 equals 2 * 3.0
7 is a prime number
8 equals 2 * 4.0
9 equals 3 * 3.0

Leave a Reply