How to Use the if…elif Statement in a Python Application

By John Paul Mueller

Your Python application may get to the point where you need to use the elif clause. You go to a restaurant and look at the menu. The restaurant offers eggs, pancakes, waffles, and oatmeal for breakfast. After you choose one of the items, the server brings it to you. Creating a menu selection requires something like an if…else statement, but with a little extra oomph.

In this case, you use the elif clause to create another set of conditions. The elif clause is a combination of the else clause and a separate if statement. The following steps describe how to use the if…elif statement to create a menu.

1Open a Python File window.

You see an editor in which you can type the example code.

2Type the following code into the window — pressing Enter after each line:

print("1. Red")
print("2. Orange")
print("3. Yellow")
print("4. Green")
print("5. Blue")
print("6. Purple")
Choice = int(input("Select your favorite color: "))
if (Choice == 1):
 print("You chose Red!")
elif (Choice == 2):
 print("You chose Orange!")
elif (Choice == 3):
 print("You chose Yellow!")
elif (Choice == 4):
 print("You chose Green!")
elif (Choice == 5):
 print("You chose Blue!")
elif (Choice == 6):
 print("You chose Purple!")
else:
 print("You made an invalid choice!")

The example begins by displaying a menu. The user sees a list of choices for the application. It then asks the user to make a selection, which it places inside Choice. The use of the int() function ensures that the user can’t type anything other than a number.

After the user makes a choice, the application looks for it in the list of potential values. In each case, Choice is compared against a particular value to create a condition for that value. When the user types 1, the application outputs the message “You chose Red!”. If no option is correct, the else clause is executed by default to tell the user that the input choice is invalid.

3Choose Run→Run Module.

You see a Python Shell window open with the menu displayed. The application asks you to select your favorite color.

4Type 1 and press Enter.

The application displays the appropriate output message.

5Repeat Steps 3 and 4, but type 5 instead of 1.

The application displays a different output message — the one associated with the requested color.

6Repeat Steps 3 and 4, but type 8 instead of 1.

The application tells you that you made an invalid choice.

7Repeat Steps 3 and 4, but type Red instead of 1.

The application displays the expected error message. Any application you create should be able to detect errors and incorrect inputs.