Code of the Day

Making decisions — if, elif, else

Programs that do the same thing every time are not very useful. Conditionals let your code respond to different situations.

First Steps10 min read
By the end of this lesson you will be able to:
  • Write an if / elif / else chain that branches on a condition
  • Use comparison operators to form boolean conditions
  • Combine conditions with and, or, not

So far every program you have written does exactly the same thing every time you run it. That is fine for a calculator, but real programs need to respond — to show a different message depending on a user's score, to skip a step when a value is missing, to keep asking for input until the user types something valid.

The tool for this is the conditional statement: a branch in the road where the program checks a condition and takes one path or the other.

if, elif, else

The simplest conditional checks one condition:

temperature = 22

if temperature > 30:
    print("It is hot today.")

If the condition temperature > 30 is True, the indented block runs. If it is False, the block is skipped entirely.

Add else for a fallback:

if temperature > 30:
    print("It is hot today.")
else:
    print("Not too hot.")

Add elif (short for "else if") to check multiple conditions in sequence:

if temperature > 30:
    print("Hot")
elif temperature > 15:
    print("Comfortable")
elif temperature > 0:
    print("Cold")
else:
    print("Freezing")

Python checks each condition in order and runs only the first branch that matches. Once one branch runs, the rest are skipped.

Indentation is not optional in Python — it is syntax. The body of each branch must be indented by the same amount (four spaces is standard). A wrong indent level either causes an IndentationError or silently puts code in the wrong branch.

Comparison operators

Conditions are built from comparisons that produce True or False:

OperatorMeaning
==equal to
!=not equal to
<less than
>greater than
<=less than or equal to
>=greater than or equal to

Note the difference between == (comparison, asks a question) and = (assignment, sets a variable). Confusing them is one of the most common beginner mistakes.

Combining conditions with and, or, not

You can join conditions:

age = 20
has_ticket = True

if age >= 18 and has_ticket:
    print("You may enter.")

if not has_ticket:
    print("Please buy a ticket first.")
  • and — both conditions must be True
  • or — at least one condition must be True
  • not — flips True to False and vice versa
Python — editable, runs in your browser

Edit the value of temp and run again to see which branch activates.

Exercise

Label a numberPython

Write a function label(n) that returns 'positive' if n > 0, 'negative' if n < 0, and 'zero' if n == 0.

label(5)'positive'label(-3)'negative'label(0)'zero'

Where to go next

Next: loops — repeating an action many times without copying code.

Finished reading? Mark it complete to track your progress.

On this page