0

How does the else: condition work after a for loop in Python? I thought that else can work only after an if condition.

for i in range(5):
     print(i)
else:
    print("done")

I don't know how or why it works.

Capybara
  • 453
  • 1
  • 4
  • 13
  • Check this: https://www.geeksforgeeks.org/using-else-conditional-statement-with-for-loop-in-python/ – Sourabh Burse Dec 06 '22 at 21:35
  • 1
    Does this answer your question? [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Pranav Hosangadi Dec 06 '22 at 21:40

1 Answers1

4

The else clause of a for loop is executed if the loop terminates because the iterator is exhausted, i.e., if a break statement is not used to exit the loop. From the documentation:

When the iterator is exhausted, the suite in the else clause, if present, is executed, and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there is no next item.

Compare

for i in range(5):
    pass
else:
    print("Iterator exhausted")

with

for i in range(5):
    break
else:
    print("Iterator exhausted")
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I recall reading somewhere that the idea of such a finalizing clause in a `for` loop is due to Knuth, the choice of `else` as the keyword being that the `break` statement would virtually always guarded by an `if` statement, and the `else` clause being executed if the condition is never executed. I am not aware of other languages implementing such a feature prior to Python, though, nor can I find a citation for Knuth as the inventor. – chepner Dec 06 '22 at 21:54