The else: statement is an optional default statement that follows an if, or elif statement or while, or for loop. The code contained in the else: block will only execute when the initial if and elif, while or for conditions are False. It is optional because it is not always necessary to have code that executes by default when a conditional statement is False.
Python allows the use of else after any conditional statement which makes it a perfect place to perform 'clean-up' tasks after exiting a while: or for: loop. When preceded by a while or for loop the else: statement is simply executed after the loop is finished.
if condition:
code block
else:
code block # only executes when if condition is False
if condition:
code block
elif condition2:
code block
else:
code block # only executes when all if... elif. conditions are False
while condition:
code block
iterator
else:
code block # executes when while loop completes
for x in iterable:
code block
else:
code block # executes when for loop completes
code block : any block of code indented any amount of space or tab stops
code block : Executes indented code block
code.py output:
a is greater than or equal to b
a is greater than b
b is equal to 5
b is equal to 4
b is equal to 3
b is equal to 2
b is equal to 1
while loop finished, resetting b
b is equal to 5
x is equal to 0
x is equal to 1
x is equal to 2
x is equal to 3
x is equal to 4
For loop finished