9/1/26About 2 minAbout 240 words
Concept: else and elif
Should an if statement need to execute code when the condition is False, an else statement can be used to define a block of code that will run in that case.
If the else statement must also conditionally execute code, an elif statement can be used instead. If the condition for the elif statement is True, the code block beneath it will be executed; if it is False, the program will continue to the next elif or else statement (if there are any).
The number of elif statements is unlimited, but there can only be one else statement, and it must be the last statement. There can also only be one if statement, and it must be the first statement.
if condition1:
# This code runs only if condition1 is True
do_something()
elif condition2:
# This code runs only if condition1 is False and condition2 is True
do_something_else()
elif condition3:
# This code runs only if condition1 is False and condition3 is True
do_something_different()
else:
# This code runs only if both condition1, condition2 and condition3 are False
do_something_as_a_last_resort()