Making decisions in Python

Module 3 · Making decisions in Python · Lesson 4 of 7

Conditions and conditional execution

Now we put answers to work. The if statement runs a block of code only when its condition is True. Write if, a condition, a colon — then indent the lines that should run.

temperature = 35
if temperature > 30:True
print("Hot!")
else:
print("Nice.")
output
Hot!

The condition is True, so only the indented if block runs — the else is skipped.

That indentation isn't decoration — it's how Python knows which lines belong to the if. Indented lines run only when the condition holds; lines back at the left margin run no matter what.

Add an else for the opposite case — code that runs when the condition is False. And when there are several possibilities, chain them with elif (“else if”): Python checks each condition in turn and runs the first one that's True, then stops.

Run it yourselfruns in your browser · Python
main.py

Change temperature to something cooler and run it again — the program takes the other branch. Notice "Done." prints every time, because it isn't indented under the if.