LESSON 07 · BEGINNER PATH10 min

Conditions

Choose which code runs using comparisons and if, elif, and else.

Video coming to YouTube

Work through the full lesson and run its code while the video is being prepared for publication.

Understand the concept

A condition is an expression that Python evaluates as true or false. An if block runs only when its condition is true. Use elif for another test and else for the remaining case.

A colon ends each branch header, and indentation marks the statements inside that branch. Use == to compare values; = assigns a value to a name.

  • if, elif, and else
  • Boolean comparisons
  • Indented blocks

See it step by step

Read the code, predict the output, then compare it with the result.

01. Choose one branch

PYTHON
temperature = 30
if temperature >= 30:
    print("Hot")
else:
    print("Mild")
EXPECTED OUTPUT
Hot

The condition is true, so Python runs the indented first branch and skips else.

02. Use elif

PYTHON
points = 75
if points >= 90:
    print("Excellent")
elif points >= 60:
    print("Passed")
else:
    print("Try again")
EXPECTED OUTPUT
Passed

Python checks the conditions in order. Only the first matching branch runs.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnAdd a score == 100 branch before score >= 90 so an exact 100 prints 'Perfect'. Set score to 100 and run the program to test it.
Need a hint?

Place if score == 100 first. Change the old if score >= 90 to elif score >= 90, keep the remaining elif and else, then test with score = 100.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.What does an if block do when its condition is false?

    02.Which operator compares two values for equality?

    03.What is not False?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Missing colon

    COMMON MISTAKE
    score = 75
    if score >= 60
        print("Passed")
    FIX
    score = 75
    if score >= 60:
        print("Passed")

    What happens: SyntaxError on the if line.
    End the if header with a colon.

    Missing indentation

    COMMON MISTAKE
    score = 75
    if score >= 60:
    print("Passed")
    FIX
    score = 75
    if score >= 60:
        print("Passed")

    What happens: IndentationError after the if header.
    Indent statements that belong to the branch.