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.
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.
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 theelse
clause’s suite. Acontinue
statement executed in the first suite skips the rest of the suite and continues with the next item, or with theelse
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")