Use else statement in loops
You can use the else statement in the for and while loops in Python. The else statement is optional and executes if the loop iteration completes normally. If the loop is terminated with a break statement, the else statement will not be executed.
Consider the following example:
for currentLetter in 'Hello world!': print('The current letter is', currentLetter) else: print('All letters were printed.')
Here is the output:
>>> The current letter is H The current letter is e The current letter is l The current letter is l The current letter is o The current letter is The current letter is w The current letter is o The current letter is r The current letter is l The current letter is d The current letter is ! All letters were printed. >>>
The simple example above printed all the letters in the Hello world! string. Because the loop iteration completed normally, the else statement was also executed and the text All letters were printed. was printed to the screen.
Now consider the example in which the code inside the else statement will not be executed:
for currentLetter in 'Hello world!': print('The current letter is', currentLetter) if currentLetter == 'w': break else: print('All letters were printed.')
The output:
>>> The current letter is H The current letter is e The current letter is l The current letter is l The current letter is o The current letter is The current letter is w >>>
Notice how the for loop was terminated when the letter w was encountered. Because the loop iteration wasn’t completed normally, the else statement wasn’t executed.