Control FlowBeginner8 min27 / 63

if / elif / else

Learn how to make your Python programs make decisions using if, elif, and else — the building blocks of all program logic.

Every useful program needs to make decisions. Should we show an error message or a success message? Is the user old enough? Did they guess the right number?

In Python, we use if statements to ask a yes-or-no question and run different code depending on the answer. This is one of the most important ideas in all of programming.

See it in action

Visual walkthrough1 / 5
1

Code That Makes Decisions

Every useful program needs to choose: show an error or a success? Let the user in or not? `if` statements are how Python picks a path — they are the heartbeat of all program logic.

if / elif / else is used in almost every real program ever written.

#Your First if Statement

An if statement checks whether a condition is True. If it is, Python runs the indented block of code beneath it. If not, Python skips it entirely.

The structure always looks like this:

`` if condition: do something ``

Notice the colon at the end of the if line, and the 4-space indent on the next line. Both are required.

The message prints because 35 > 30 is True.
temperature = 35

if temperature > 30:
    print("It's hot outside!")

print("Done checking the weather.")
Think of it like

Think of it like a gate

Imagine a bouncer at a club. They check your ID. If you're old enough, you get in. The if statement is that gate — only the code inside the indented block runs when the condition passes.

#Indentation is Everything

Python uses indentation (spaces at the start of a line) to know which lines belong inside an if block. Most Python code uses 4 spaces per level. This is not just style — it changes how your program behaves.

Common mistake

Indentation errors will crash your program

Forgetting to indent, or mixing tabs and spaces, causes an IndentationError. Always use 4 spaces (not a tab character) for each level. Most editors handle this for you automatically.

score is 45, so the indented lines are skipped. The last line always runs.
score = 45

if score >= 50:
    print("You passed!")   # indented — inside the if
    print("Great work.")   # also inside the if

print("Thanks for playing.")  # NOT indented — always runs

#Adding else: a Fallback

Sometimes you want to do one thing if a condition is true, and a different thing if it is false. That is exactly what else is for. It runs when the if condition is False.

16 >= 18 is False, so the else block runs.
age = 16

if age >= 18:
    print("You can vote!")
else:
    print("You cannot vote yet.")

#elif: Checking More Options

What if you have more than two possibilities? Use `elif` (short for "else if") to check additional conditions, one after another. Python stops at the first one that is True.

Python checks each condition top to bottom and stops at the first True one.
grade = 75

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
else:
    print("Below C")
Tip

Order matters with elif

Python checks conditions in order and stops as soon as one matches. Put your most specific conditions first. If you put grade >= 70 before grade >= 90, a score of 95 would print "C" — not what you want!

#Truthy and Falsy Values

Python does not only accept True or False in an if condition. Many values are treated as truthy (count as True) or falsy (count as False).

  • Falsy: 0, "" (empty string), [] (empty list), None
  • Truthy: any non-zero number, any non-empty string or list

This lets you write very clean, readable checks.

An empty string is falsy, so the else branch runs.
name = ""

if name:
    print("Hello,", name)
else:
    print("No name provided.")

#Nested if Statements

You can put an if statement inside another if block. This is called nesting. It is useful when you need to check one thing only after a first condition passes.

The inner if only runs because has_ticket is True.
has_ticket = True
is_vip = False

if has_ticket:
    print("Welcome!")
    if is_vip:
        print("Enjoy the VIP lounge.")
    else:
        print("Head to the general area.")
else:
    print("Sorry, no ticket, no entry.")
Watch out

Don't nest too deeply

More than 2-3 levels of nesting makes code hard to read. If you find yourself indenting 5 times, look for a way to simplify using elif or by breaking logic into separate functions.

#The One-Line Conditional Expression

Python has a compact way to write a simple if/else in a single line, called a conditional expression (sometimes called a ternary expression). It follows this pattern:

`` value = thing_if_true if condition else thing_if_false ``

Use this only for simple choices — it can hurt readability if overused.

A concise way to assign a value based on a condition.
points = 120
label = "Winner" if points >= 100 else "Keep trying"
print(label)
Quick check

What will this code print? ```python x = 10 if x > 20: print("big") elif x > 5: print("medium") else: print("small") ```

Key takeaways

  • Use `if condition:` (with a colon) to run code only when a condition is True.
  • Always indent the code block inside an `if`, `elif`, or `else` by 4 spaces — indentation is how Python knows what belongs inside.
  • `elif` lets you check multiple conditions in order; Python stops at the first True one.
  • `else` is the fallback that runs when no previous condition matched.
  • For a simple two-way choice in one line, use the conditional expression: `a if condition else b`.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
score = 45

if score >= 50:
    print("You passed!")
    print("Great work.")

print("Thanks for playing.")
Fix the bug#2

This code should print "You can vote!" when age is 20, but it causes an error instead. What is wrong?

fix-bug
age = 20

if age >= 18
    print("You can vote!")
Fill in the blank#3

Complete the code so it prints "Warm" when temperature is 25, "Cold" when it is below 15, and "Just right" for anything in between.

temperature = 25

if temperature >= 30:
    print("Hot")
 temperature >= 15:
    print("Warm")
:
    print("Cold")
Reorder the lines#4

Put these lines in the right order so the program checks whether a number is positive, negative, or zero and prints the correct label.

1
if number > 0:
2
    print("Negative")
3
    print("Positive")
4
number = -4
5
elif number < 0:
6
    print("Zero")
7
else:
Your turn
Practice exercise

Write a program that asks for a number (you can just assign it directly, no need for input) and prints: "Positive" if it is greater than 0, "Negative" if it is less than 0, or "Zero" if it equals 0. Then, on the same run, also print "Even" or "Odd" for non-zero numbers (you can skip this check for zero).

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable