← Intro to programming with Python

if, elif and else

Run different code depending on a condition.

Start this lesson

An if statement runs some lines only when a condition is True. Think of a thermostat: IF it is cold, turn on the heat. After the condition comes a colon, and the lines that belong to the if are indented (pushed in by 4 spaces). The indentation is how Python knows which lines are inside. else gives an "otherwise" path, and elif ("else if") lets you check more conditions in order. Python stops at the FIRST one that is True.

temp = 12
if temp < 0:
    print("Freezing! Wear a heavy coat.")
elif temp < 15:
    print("Chilly. Bring a jacket.")
else:
    print("Nice and warm.")
print("Have a good day")

12 is not below 0, but it is below 15, so this shows Chilly. Bring a jacket. The last line is not indented, so it runs no matter what.

Common mistake: forgetting the colon at the end of the if line, or forgetting to indent. Both give an error.

Order matters with elif. If you test temp < 15 before temp < 0, a freezing day would say "Chilly", because Python stops at the first match.

else never has a condition. It simply catches everything that did not match.