Pulsars
0 %
Log inSign up

Conditions

Making decisions with if / elif / else

Making decisions with if / elif / else

A program often needs to react differently depending on the situation: that's the role of conditions. In Python, the basic conditional structure is if:

note = 12
if note >= 10:
    print("Admitted")

This program displays Admitted only if the variable note is greater than or equal to 10. If the condition is false, the indented block under the if is simply skipped.

To handle an alternative case, we add else:

note = 8
if note >= 10:
    print("Admitted")
else:
    print("Not admitted")

And when there are several possible cases, we use elif (a contraction of else if) as many times as needed:

note = 15
if note >= 16:
    print("High distinction")
elif note >= 14:
    print("Distinction")
elif note >= 10:
    print("Admitted, no distinction")
else:
    print("Not admitted")

Python tests the conditions in order, and executes the block of the first true condition it encounters, then stops there: it does not examine the following conditions. Here, note = 15 matches the second condition (note >= 14), so the program displays Distinction, without even looking at the following conditions.

A crucial point in Python: indentation (the spaces at the start of lines) is not decorative, it is part of the syntax! The lines indented under an if, an elif or an else form the block of instructions that belongs to it. An incorrect indentation level causes an error or incorrect behavior.