LearnPy Hub
Control FlowBeginnerLesson 7 of 32

If…Else

Watch the ideaif, elif, else: choosing a path
marks = 72
if marks >= 80:
    print("A+")
elif marks >= 50:
    print("Pass")
else:
    print("Try again")
marks72
if marks >= 80
elif marks >= 50
else

Python checks the conditions from top to bottom.

1Level 1 · BasicsBasics

Real programs make decisions: show "Pass" or "Fail", let a user in or not, charge a discount or not. if, elif and else let your program choose what to do.

The if statement

marks = 75
if marks >= 40:
    print("You passed!")
print("Done")

Three things to notice:

  1. The condition (marks >= 40) is followed by a colon.
  2. The lines that belong to the if are indented by 4 spaces. That indented group is called a block.
  3. The block runs only when the condition is True. print("Done") isn't indented, so it always runs.

else: the other way

if marks >= 40:
    print("Pass")
else:
    print("Fail")

elif: more than two choices

elif means "else if". Python checks the conditions from top to bottom and runs the first block whose condition is True, then skips the rest:

if marks >= 80:
    grade = "A+"
elif marks >= 70:
    grade = "A"
elif marks >= 60:
    grade = "B"
else:
    grade = "F"

Order matters. If you checked marks >= 60 first, a mark of 85 would get a B!

Combining conditions

Use and, or and not from the Operators lesson: if age >= 18 and has_id:. You can also put an if inside another if (nesting), but combined conditions are often easier to read.

One-line choice

For simple either/or values there's the conditional expression: status = "even" if n % 2 == 0 else "odd".

Key points: end each condition with a colon; indent the block; elif chains stop at the first True condition; else catches everything left.

See it in actionPython picks one branch

Watch which lines the arrow visits: the other branches are skipped.

Step-by-step

Try it yourselfExample 1: Pass or fail

Change marks to 30 and run again.

example_1.py
Output appears here
Fill in the blanks

Pass mark

The pass mark is 40. Fill the blanks so a score of 55 prints Pass.

blanks.py
score = 55
if score  40:
    print("Pass")
:
    print("Fail")

Example 2: Grades with elif

Only the first matching branch runs. Try 95, 65 and 20.

example_2.py
Output appears here
Fix the bug

Missing pieces

This should print Cold for 12 degrees, but Python reports an error. Fix it.

buggy.py
Fill in the blanks

Grade ladder

Fill the blanks so a mark of 72 prints B.

blanks.py
mark = 72
if mark >= 80:
    print("A")
 mark >= 60:
    print("B")
:
    print("C")

Example 3: Decisions from user input

Change the number in the Input box.

example_3.py
Output appears here
Your turn

The bigger number

Read two whole numbers (one per line) and print the bigger one. If they are equal, print Equal. Don't use max().

Example input4 9Expected output9

my_code.py

Example 4: Combining conditions

A ticket is free for children under 5 and seniors 60 or over.

example_4.py
Output appears here
Your turn

Leap year

Read a year and print Leap or Not leap. A year is a leap year if it divides by 4, except years that divide by 100 unless they also divide by 400.

Example input2024Expected outputLeap

my_code.py

2Level 2 · IntermediateNested decisions and cleaner conditions

Nested if

An if inside another if handles decisions that depend on earlier ones, like "is it a leap year?": divisible by 4, but not by 100, unless also by 400.

Truthiness in conditions

Empty things and zero are false: if name: means "if name is not empty", and if not name: means "if name is empty". You rarely need == True or len(name) > 0.

Guard clauses

Check the bad cases first and stop early. This keeps the main logic un-indented and easy to read.

in instead of many or

if letter in "aeiou": is clearer than letter == "a" or letter == "e" or ....

See it in actionThe leap year decision tree

Watch which branches the arrow enters for 1900. Then try 2000 and 2024 in the editor below.

Step-by-step

Example 5: The same rule in one line

Combined conditions can replace nesting. Try 2000, 2023 and 2024 and check the answers match the decision tree above.

example_5.py
Output appears here

Example 6: Guard clauses and truthiness

Try name = "", then age = -3, then age = 3, then day = "Tue". The bad cases are checked first, so the price logic only runs for good input.

example_6.py
Output appears here

3Level 3 · Advancedmatch-case and the order of branches

Structural pattern matching

Since Python 3.10, match compares a value against patterns. It can match literal values, several at once (case "q" | "quit":), and add a guard (case n if n < 0:). case _: catches everything else. (Once you know lists, match can even check their shape.)

Order matters in a chain

Python takes the first branch whose condition is true and skips the rest. For grade bands, test the highest band first; if you test mark >= 33 first, an 85 would get a D.

Bands with chained comparisons

When branches can't be ordered, give each one both limits: 70 <= mark < 80. Then the order no longer matters.

Example 7: A tiny command interpreter with match

Change command to "n", "look", "dance" or "exit". Then add a "jump" command.

example_7.py
Output appears here

Example 8: Grades with match and guards

The highest band is tested first, so the first true guard wins. Try 95, 52, 33 and 12.

example_8.py
Output appears here
Common mistakeForgetting the colon after if x > 3, or mixing tabs and spaces, gives a SyntaxError or IndentationError. Also, if x = 5: is wrong: use == to compare.
Exercise · predict the output

What does this print?

x = 15
if x > 10:
    print("big", end=" ")
if x > 5:
    print("medium")
Quick quiz · 5 questions
1. Which keyword means "else if" in Python?
2. What marks the block of code that belongs to an if?
3. In an if/elif/else chain, how many blocks can run?
4. What is printed when n is 0? if n > 0 then print("A"), elif n == 0 then print("B"), else print("C").
5. What does "yes" if 3 > 5 else "no" evaluate to?
Ready to practice if…else?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python If…Else · LearnPy Hub