It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Creating Multiple Branches with elif

So far, we've looked at two-way decisions using if and else. But sometimes, we want to check more than two conditions — this is where elif (short for else if) comes in.

The elif Statement

elif lets you check multiple conditions, one after another. If the first if is false, Python checks the elif. If none match, it finally runs the else (if there is one).

Syntax:

if condition1:
    # runs if condition1 is true
elif condition2:
    # runs if condition2 is true
elif condition3:
    # runs if condition3 is true
else:
    # runs if none are true

Python checks the conditions from top to bottom, and stops at the first one that is true.

Example:

score = 85

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")

Output

Grade: B

Why Use elif?

Without elif, you'd have to nest if statements, which makes code harder to read.

Compare this:

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

To this:

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

Much cleaner, right?

Real-world Example

day = "Monday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
elif day == "Friday":
    print("Almost weekend!")
else:
    print("It's a weekday.")

elif Chains Can Be as Long as Neede

You can use as many elif statements as you want — Python will evaluate them in order until it finds a match.

Exercise: Try It Yourself!

Write a program that asks the user for a number between 1 and 12 and prints the corresponding month name. If the number is not in the range, print "Invalid month number".

Sample output

Enter month number: 4
April

Hint:

Use int(input(...)) to convert user input into a number.