2

We know Python loops have extra features that are not available in most other programming languages. You can put an else block immediately after a loop's repeated interior block.

for i in range(3):
    print('Loops', i)
else:
    print('Else block!')

Output

Loops 0
Loops 1
Loops 2
Else block!

Surprisingly, the else block runs immediately after the loop finishes. Now if I set a break condition then the following output is showing.

for i in range(3):
    print('Loops', i)
    if i == 1:
        break
else:
    print('Else block!')

Output

Loops 0
Loops 1

My question is, why else is skipped. In that case, The loops aren't completed?

mhhabib
  • 2,975
  • 1
  • 15
  • 29

2 Answers2

1

Because the else for for works similar to that of try. It runs only if the for loop is not broken. From the official document:

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.

Chris
  • 29,127
  • 3
  • 28
  • 51
0

In fact, the intended use for this syntax is to make search loops.

Once you get an item that meets your conditions, you can break and so leave out the for without passing by the else.

However, if you don't find anything, you may want to make extra processing related to the search failure, and so the else statement follows.

Synthase
  • 5,849
  • 2
  • 12
  • 34