Else Statement and Loops¶
You can use an else statement after a for
or while
loop. The code in this else
statement is executed if the loop completed without being terminated.
The only time the else
part will not be executed is if you break
out of a loop:
Worked Example
A common use for this structure is if you’re searching for an object. Consider this example where we are trying to find a 'fish'
in a list:
Of course, finding a particular object in a list is quicker and simpler using:
but for more complex procedures this may not be an option.