Python elif

Learn how to use if / else before you read about elif.


Rule when using if / elif / else:

  • The first branch must be if.
  • You can have as many elif branches in the middle as you like.
  • If you include an else branch, it must be the last branch.
  • if and elif require conditions. else cannot have a condition.
  • Each time your code starts with if, a new series of if/elif/else branches begins, and the previous one ends.

elif means “else if”

If you need your code to choose between more than two code blocks, you can add elif branches in the middle of your if/else structure.

Personality Quiz Example:

word = input('Type a word and I will determine your personality:')

if word == "":
    print("You didn't type anything.")
    print('Your personality is: Absent Minded')
elif word.isdigit():
    print("You only typed numbers.")
    print("Your personality is: Numerical")
elif not word.lower().islower():
    print("You didn't type any letters.")
    print('Your personality is: Rebellious')
elif len(word) > 7:
    print('That is a long word.')
    print('Your personality is: Intellectual')
elif word == 'potato':
    print('You typed "potato."')
    print('Your personality is: Entrepreneurial')
else:
    print('Your word contains at least one letter.')
    print('Your personality is: Charming')
print('Thanks for participating.')

Exactly one branch will execute. When one of the branch conditions is true, it will execute that branch’s code block and skip the rest. The code resumes with the next line of code after the else branch.

This is preferred for a personality quiz, because it would confusing if the personality quiz gave zero answers or three different answers.

Practice Exercises:

1) Run the starter code multiple times. Figure out how to make the program output each of the possible personality choices.

2) Figure out a response that fits at least two of the conditions. Before you run the code, predict what the program will do. Which one of the branches executed?

3) Change if to elif in the second line of code. Run the program. What happens? What does this error mean?

    elif word == "":
       ^
SyntaxError: invalid syntax

Pay attention to that hat character, ^,  pointing up to elif.  Python is telling you that you can’t use elif in this situation. That’s because there is no if branch to go along with it, before the elif. That breaks the language rules, which is why it says “invalid syntax.”

Change elif back to if to get the code working again.

4) Change every elif to just if. Run the code again and type a response that fits more than one condition. What happens?

Apart from the fact that you can get more than one Personality type now, you should notice something else about the end of the program.

The program always says you are charming. This is because the last two branches now looks like this:

if word == 'potato':
    print('You typed "potato."')
    print('Your personality is: Entrepreneurial')
else:
    print('Your word contains at least one letter.')
    print('Your personality is: Charming')

Because this is an if/else structure, one of these two branches will always execute. Therefore, the program says you’re charming unless you typed “potato.”

Change the program back to the way it was before.

5) Disable the else branch near the end of the program by commenting it out. Add # characters to the start of each line. This causes the program to ignore these lines of code.

#else:
#    print('Your word contains at least one letter.')
#    print('Your personality is: Charming')

Now run the program and enter “cheese” as your response. What happens?

This should show you that it’s possible for none of the branches to execute if all of the conditions are False.

Sometimes that is desirable, but for many programs you want something to execute no matter what. That’s what else is for: this is the branch that should execute when every if / elif condition is False.

6) Put the else branch back into the code, but add a condition to it:

else word == "bicycle":
    print('Your word contains at least one letter.')
    print('Your personality is: Charming')

What happens? How will you be able to figure out what’s wrong if you get this type of error?

    else word == "bicycle":
            ^
SyntaxError: invalid syntax

The hat character points to the start of the condition that comes after else. Putting a condition after else breaks the language rules, so you have an “invalid syntax” error.  You don’t need a condition after else, because an else branch needs to execute no matter what if all the previous ones were false.

7) Switch the order of some of the elif branches in your code.

Run the code a bunch of times, attempting to get each possible personality response. Note: it may not be possible to get them all.

For example, if “didn’t type any letters” comes before “only typed numbers,” it will now be impossible to execute the “only typed numbers” branch.  Try it! This is because any possible all-number response like “234876823476” will first trigger the “didn’t type any letters” branch, which causes the “only typed numbers branch” to be skipped.

Hopefully this example lets you know that the order of your if/elif conditions can be important for some programs.

For some other cases, the order of the elif branches determines which response will happen when your response fits two or more criteria, even though it’s still possible for each branch to execute.

For example, move the “len(word) > 7” branch so that it’s the first elif branch. Now you can type a long number and get the “Intellectual” response. Your program behaves differently than it did before – with the original code, you would have gotten a “Numerical” personality.