πŸ”€
CodingπŸ”¬ Ages 11-13Beginner 12 min read

Python: if, elif, else

Master Python decisions with if, elif and else: comparison operators, branching, why elif beats stacked ifs, chained conditions with and/or, and indentation. Runnable code, a worked example and quiz.

Key takeaways

  • if runs a block only when its condition is True; else runs when it is False
  • elif lets you test extra conditions in order, choosing exactly one branch
  • Comparisons like ==, !=, <, >, <=, >= produce the True/False values conditions need
  • Indentation decides which lines belong to a branch, so it must be consistent

Programs that make decisions

So far, the programs you write probably run every line, top to bottom, the same way every time. But real programs need to choose. A game checks if you have enough points to win. A login checks if the password is correct. A shop checks if you are old enough to buy something. These choices are called conditionals, and in Python they are built from three keywords: if, elif, and else.

This lesson goes deeper than a first look at decisions. If if is brand new to you, skim conditionals in Python first; here we focus on combining if, elif, and else correctly and avoiding the classic traps.

Conditions: the True/False questions

Every decision rests on a condition β€” an expression that is either True or False. We build conditions with comparison operators:

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal to5 != 3True
>greater than2 > 9False
<less than2 < 9True
>=greater than or equal7 >= 7True
<=less than or equal4 <= 3False

The most common beginner bug is confusing = and ==:

  • x = 5 assigns the value 5 to the variable x.
  • x == 5 asks "is x equal to 5?" and gives back True or False.

Inside an if, you almost always want the double ==.

The if statement

An if runs a block of code only when its condition is True:

temperature = 32

if temperature > 30:
    print("It's hot!")
    print("Stay hydrated.")

Reading it carefully:

  • if temperature > 30: is the condition, ending in a colon :.
  • The two indented lines are the block that runs only if the condition is True.
  • Because 32 > 30 is True, both lines print.

If the temperature were 18, the condition would be False and Python would simply skip the whole block.

Indentation is not optional

In Python, indentation (the spaces at the start of a line) decides which lines belong to the if. Lines indented under the if run together as the block. The moment a line goes back to the left, it is outside the if and runs every time:

if temperature > 30:
    print("It's hot!")      # part of the if
print("Have a nice day.")   # NOT part of the if β€” always runs

Use four spaces per level, and be consistent. Mixing indentation causes an IndentationError.

Adding else: the fallback

An else block runs when the if condition is False. It gives you an "otherwise" path:

age = 15

if age >= 18:
    print("You can vote.")
else:
    print("Too young to vote.")

Exactly one of the two blocks runs. Since 15 >= 18 is False, the else block runs and prints "Too young to vote." There is no condition on else β€” it simply catches every case the if missed.

elif: choosing among many options

What if there are more than two possibilities? Stacking separate if statements is clumsy and can misbehave. Instead, use elif (short for "else if") to test extra conditions in order:

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Here is the key behaviour: Python checks the conditions top to bottom and runs only the first one that is True, then skips all the rest.

  1. score >= 90? 75 is not, so move on.
  2. score >= 80? 75 is not, so move on.
  3. score >= 70? 75 is, so print "Grade: C" and stop β€” the remaining elif and else are skipped entirely.

This ordering is why the chain works. We test the highest grade first and work down, so the first match is always the right one.

Why elif beats stacked ifs

Compare these two versions. They look similar but behave very differently:

# With elif β€” exactly ONE message
if score >= 70:
    print("You passed.")
elif score >= 50:
    print("Almost there.")

# With two separate ifs β€” can print BOTH
if score >= 70:
    print("You passed.")
if score >= 50:
    print("Almost there.")

With a score of 75 and separate ifs, both conditions are True, so you'd print "You passed." and "Almost there." β€” usually not what you want. With elif, only the first match runs. When the options are alternatives, reach for elif.

Combining conditions with and / or

Sometimes one test is not enough. You can join conditions with and and or:

  • and is True only when both sides are True.
  • or is True when at least one side is True.
age = 16

if age >= 13 and age <= 19:
    print("You are a teenager.")

if age < 13 or age > 19:
    print("You are not a teenager.")

The first condition needs age to be at least 13 and at most 19. Since 16 fits both, it prints "You are a teenager." This is far cleaner than nesting two separate if statements.

Worked example: a ticket price calculator

Let's build a complete program that decides a cinema ticket price from the customer's age, using everything above.

age = int(input("How old are you? "))

if age < 5:
    price = 0
    message = "Free entry for little ones!"
elif age <= 17:
    price = 8
    message = "Child ticket."
elif age >= 65:
    price = 6
    message = "Senior discount applied."
else:
    price = 12
    message = "Adult ticket."

print(message)
print(f"Your ticket costs {price} pounds.")

Tracing it for a 70-year-old:

  1. int(input(...)) reads the age and converts the text to a number β€” 70.
  2. age < 5? No. Skip.
  3. age <= 17? No. Skip.
  4. age >= 65? Yes. Set price = 6 and the senior message, then skip the else.
  5. The two prints show "Senior discount applied." and "Your ticket costs 6 pounds."

Notice the order matters: because the chain checks in sequence and stops at the first match, each branch only runs when all the earlier ones failed. That is what lets elif age <= 17 quietly mean "between 5 and 17" β€” anyone under 5 was already caught above.

Try it yourself

Write a program that gives feedback on a quiz score out of 100:

  • Read the score with int(input(...)).
  • Use an if / elif / else chain to print: "Outstanding!" for 90+, "Great job!" for 70–89, "Keep practising." for 50–69, and "Let's review together." below 50.
  • Add a single combined condition using and that prints a bonus message, such as "Perfect attendance bonus!" only when the score is at least 70 and a variable attended_all is True.

Check the boundaries carefully β€” what should happen at exactly 70 or exactly 90? Once your branches choose correctly every time, you are ready to repeat actions automatically with loops and repeats.

Quick quiz

Test yourself and earn XP

What is the difference between = and == in Python?

In an if / elif / elif / else chain, how many branches run?

What does this print? ``` x = 7 if x > 10: print("big") elif x > 5: print("medium") else: print("small") ```

When is the condition `age >= 13 and age <= 19` True?

Why does indentation matter after an if statement?

FAQ

Use elif when only one option should win and the conditions are related, like grading a score. Separate ifs each get checked independently, so more than one can run. An if/elif/else chain checks in order and runs exactly one branch, which is usually what you want for choosing between options.

No. else is optional. Use it when you want a fallback for every case the ifs and elifs did not catch. If doing nothing is fine when no condition matches, you can leave else out entirely.