For-Else in Python - who knew?
I love that I am still discovering Python functionality, even after coding daily for six years. This week I learnt that else clauses aren't just for if statements - they can be added to loops! The else clause will trigger if and only if the loop completed without being broken. For instance, this snippet will will print the numbers zero through nine then print 'Done!':
for i in range(10):
print(i)
else:
print('Done!')
The main use case is handling a break clause in your loop not triggering, for instance:
for number in [3,5,7,9,11]:
if number % 2 == 0:
print('Found an even number!')
break
else:
print('No even numbers found!')
This isn't an uncommon situation to want to handle and the else clause makes it so much neater.
Comments
Post a Comment