CodeBlanks Logo Icon CodeBlanks

elif and else

Learn alternatives with elif and else.

elif and else

elif (else if) adds a second condition. else runs when no condition is true:

score = 75
if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("C")

Python tries conditions in order; the first True block runs. else is always last and takes no condition.

The order of if/elif/else

In an if/elif/else chain Python checks from top to bottom. The first True condition's block runs; the rest are skipped.

temp = 25
if temp > 30: print("Hot")
elif temp > 20: print("Mild")
elif temp > 10: print("Cold")
else: print("Freezing")

The order matters: write narrow ranges first, wider ones later.

Practice Print a grade with elif/else

Assign score = 75. Write if score >= 90: print("A"), elif score >= 70: print("B"), else: print("C").

Starter code

main.py
# Grade with elif/else

Sample solution

main.py
score = 75
if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("C")

Expected output

B

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If score is 75, what does this print? if score>=90: A elif score>=70: B else: C

  • A
  • Error
  • C
  • B Correct answer

Explanation: 75 >= 90 is False, 75 >= 70 is True, so B prints.

2 Complete the else block

Question
if age >= 18:
    print("Adult")
____:
    print("Child")
Answer
if age >= 18:
    print("Adult")
else:
    print("Child")

Explanation: else runs when no condition is true.

3 Match the keywords

Term Meaning
if First condition
elif Extra condition
else Fallback
: Opening a block

All lessons in Beginner