livepython.net
CHAPTER 08If Statements
8.2  ELSE AND ELIF

Python if, else and elif Explained

else: The Other Path

An if alone does something or nothing. Add else to do something different when the condition is False:

PYTHONedit me
age = int(input())
if age >= 18:
    print("You can vote.")
else:
    print("Not yet. Wait a few years!")
OUTPUT
Not yet. Wait a few years!

Exactly one of the two blocks runs, never both, never neither.

  1. Start:
    Start
  2. Input or output:
    Read the age
  3. Decision:
    Is age 18 or more?
    yes
    Show: You can vote.
    no
    Show: Not yet.
  4. End:
    End
Vote or wait?

How to write it

  • else lines up with its if: same indentation.
  • It has no condition: it simply means "otherwise".
  • It ends with a colon, and its block is indented, just like the if block.

Even or odd

A classic example, using % from chapter 5. A number is even when dividing it by 2 leaves nothing over:

PYTHONedit me
n = int(input())
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")
OUTPUT
7 is odd

Think of a fork in a road: you must take one way or the other, and you can't take both.

Common beginner doubt: "Can I put more than one line in each block?" Yes. Each block can have as many indented lines as you need: calculations, several print()s, even another if.

if … else: one of the two blocks always runs.

your turnPredict the output

What will this print?

n = int(input()) if n % 2 == 0: print("even") else: print("odd")

The user types: 10

Your turn! What will this code show on the screen?
your turnFill the gap

Complete the other path

x = 3 if x > 5: print("big") ? print("small")

It should print: small

Which piece makes this code work?

elif: More Than Two Paths

What if there are three or more possibilities? Use elif, short for "else if":

PYTHONedit me
marks = int(input())
if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Try again")
OUTPUT
Grade B

Python checks the conditions from top to bottom:

  1. Is marks 90 or more? No.
  2. Is it 75 or more? Yes: print Grade B, and stop checking.

The else at the end catches everything that matched nothing above. It's optional.

The rules

  • One if at the start.
  • As many elif as you need, each with its own condition.
  • At most one else, at the end.
  • Only the first condition that is True runs its block. The rest are skipped, even if they're also True.

Think of a ladder: Python climbs down from the top rung and steps off at the first rung that fits.

A ticket price example

PYTHONedit me
age = int(input())
if age < 5:
    price = 0
elif age < 18:
    price = 50
else:
    price = 100
print("Ticket:", price)
OUTPUT
Ticket: 50

Each block sets price, and one print() at the end shows it. This "decide, then show once" pattern keeps the code short.

Common beginner doubt: "Do I always need an else?" No. Without one, nothing happens when no condition matches. Add an else when every case needs an answer, like a grade for every mark.

if, then elif for each extra case, then else for everything else. The first True wins.

your turnType the output

Type what this prints

t = int(input()) if t > 30: print("hot") elif t > 20: print("warm") else: print("cold")

The user types: 25

Read the code line by line, then type the output exactly.

Why the Order of elif Matters

Because only the first True condition runs, the order of your conditions can break a program. Look at this grade program with the lines in the wrong order:

PYTHONedit me
marks = 95
if marks >= 50:
    print("Grade C")
elif marks >= 75:
    print("Grade B")
elif marks >= 90:
    print("Grade A")
OUTPUT
Grade C

95 marks should be an A! But marks >= 50 is checked first, it's True, so Python prints Grade C and stops. The other conditions are never even looked at.

The fix: most specific first

Check the narrowest condition first, then work down:

PYTHONedit me
marks = 95
if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
OUTPUT
Grade A

Think of sorting coins with holes of different sizes: if the biggest hole is on top, every coin falls through it. Put the smallest hole first.

Test the edges

A good habit: test the program with values right at the edges: 89, 90, 74, 75, 49, 50. Off-by-one mistakes (> instead of >=) hide exactly there. You saw why in chapter 5: 90 > 90 is False, but 90 >= 90 is True.

Put the most specific condition first, then the wider ones.

your turnOrder the lines

Put the blocks in the right order for 95 marks to get an A

  1. print("A")
  2. print("C")
  3. elif marks >= 50:
  4. if marks >= 90:
  5. marks = 95
These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

x = 15 if x > 5: print("over 5") elif x > 10: print("over 10")
Your turn! What will this code show on the screen?

Separate ifs or an elif Chain?

Two if statements one after another are not the same as if … elif. Compare:

PYTHONedit me
n = 20
if n > 5:
    print("bigger than 5")
if n > 10:
    print("bigger than 10")
OUTPUT
bigger than 5
bigger than 10
PYTHONedit me
n = 20
if n > 5:
    print("bigger than 5")
elif n > 10:
    print("bigger than 10")
OUTPUT
bigger than 5
  • Separate ifs are independent questions. Each one is checked, and several blocks can run.
  • An if/elif chain is one question with several answers. Only one block runs.

Which one do you need?

Ask: "Can more than one of these be true and should all of them run?"

SituationUse
Pick one grade for a markif / elif / else
Pick one ticket priceif / elif / else
Give a badge for each goal reached (many can apply)separate ifs
Warn about each problem found (several can apply)separate ifs

Think of a quiz: "Which is your favourite colour?" has one answer (a chain). "Tick every colour you like" can have many (separate ifs).

One answer: use an elif chain. Several can apply: use separate ifs.

your turnPick the right idea

A game gives a badge for each goal reached: 10 points, 50 points, 100 points. A player can earn several. Which shape fits?

Think about it, then pick one.
your turnPredict the output

What will this print?

a, b = 3, 8 print(b - a)
Your turn! What will this code show on the screen?

Practice: else and elif

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 61.Python Program to Check If a Number Is Even or OddEasySolve
  2. 62.Python Program to Find the Larger of Two NumbersEasySolve
  3. 63.Python Program to Calculate a Grade from MarksMediumSolve