Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Making Decisions: if / elif / else

14 min 25 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 5 of 7 · View course roadmap
Step 1

Learn the idea

Programs become intelligent when they can choose. Python decides with if, elif and else:

Comparison operators produce booleans: == (equal), != (not equal), <, >, <=, >=. Combine conditions with and, or, not.

Indentation is the syntax. The indented block under an if only runs when the condition is True. Python convention is 4 spaces.

  • if — checked first
  • elif — checked only if everything above was False (you can chain many)
  • else — the fallback, runs if nothing matched

Where you'll use this

Every access check ('is this user an admin?'), price rule ('free shipping over €50') and form validation in every app you use is an if/elif chain. Reading them fluently is reading business logic.

Common mistakes

  • Using = instead of == in a condition — Python catches this as a SyntaxError, unlike C.
  • Forgetting the colon at the end of if/elif/else lines.
  • Inconsistent indentation — mixing tabs and spaces breaks the block structure. Configure your editor to insert 4 spaces per Tab.
  • Chaining that never triggers: checking score >= 80 before score >= 90 means the 90 branch is unreachable.

Pro tip

Python chains comparisons naturally: 18 <= age < 65 works exactly like the math notation. Also, empty containers are falsy — 'if my_list:' is the Pythonic way to test non-emptiness.

Step 2

Watch how it runs — line by line


        

Press play to watch Python execute this code, one line at a time.

Step 3

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 4

Pass the challenge +25 XP

Blank · autosaved

The starter defines temperature = 31. Print Hot if it is above 28, Mild if it is above 15 (but not hot), otherwise Cold.

Target output
Hot
PYchallenge.py
Run your code to check it…
Step 5

Check your understanding

1. Which operator tests equality?
2. When does an elif branch run?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path