Skip to content

Choosing Alternatives Using the if…else Statement

Choosing Alternatives Using the if…else Statement

Many of the decisions you make in an application fall into a category of choosing one of two options based on conditions. For example, when looking at a signal light, you choose one of two options: press on the brake to stop  or press the accelerator to continue. The option you choose depends on the conditions. A green light signals that you can continue on through the light; a

red light tells you to stop. The following sections describe how Python makes it possible to choose between two alternatives.

 

 

Understanding the if…else statement

With Python, you choose one of two alternatives using the else clause of the if statement. A clause is an addition to a code block that modifies the way in which it works. Most code blocks support multiple clauses. In this case, the else clause enables you to perform an alternative task, which increases the usefulness of the if statement. Most developers refer to the form of the if statement that has the else clause included as the if…else statement, with the ellipsis implying that something happens between if and else.

 

Sometimes developers encounter problems with the if…else statement because they forget that the else clause always executes when the condi- tions for the if statement aren’t met. It’s important to think about the con- sequences of always executing a set of tasks when the conditions are false. Sometimes doing so can lead to unintended consequences.

 

 

Using the if…else statement in an application

The SimpleIf3.py example is a little less helpful than it could be when the user enters a value that’s outside the intended range. Even entering data of the wrong type produces an error message, but entering the correct type of data outside the range tells the user nothing. In this example, you discover the means for correcting this problem by using an else clause. The following steps demonstrate just one reason to provide an alternative action when the condition for an if statement is false. This example also appears with the downloadable source code as IfElse.py.

 

 

  1. Open a Python File

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

2y.peT the following code into the window — pressing Enter after each line:

 

As before, the example obtains input from the user and then determines whether that input is in the correct range. However, in this case, the else clause provides an alternative output message when the user enters data outside the desired range.

Notice that the else clause ends with a colon, just as the if statement does. Most clauses that you use with Python statements have a colon associated with them so that Python knows when the clause has ended. If you receive a coding error for your application, make sure that you check for the presence of the colon as needed.

  1. Choose RunRun

You see a Python Shell window open with a prompt to type a number between 1 and 10.

  1. Type 5 and press Enter.

The application determines that the number is in the right range and outputs the message shown previously in Figure 7-3.

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

This time the application outputs the error message shown in Figure 7-5. The user now knows that the input is outside the desired range and knows to try entering it again.

 

 

Using the if…elif statement in an application

You go to a restaurant and look at the menu. The restaurant offers eggs, pan- cakes, 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. This example also appears with the downloadable source code as IfElif.py.

 

 

 

 

 

 

 

 

 

Figure 7-5: It’s always a good idea to provide feedback

for incorrect

input.

 

 

  1. Open a Python File

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

2y.peT the following code into the window — pressing Enter after each line:

 

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 none of the options is correct, the else clause is executed by default to tell the user that the input choice is invalid.

  1. Choose RunRun

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

  1. Type 1 and press Enter.

The application displays the appropriate output message, as shown in Figure 7-6.

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

The application displays a different output message — the one associ- ated with the requested color.

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

The application tells you that you made an invalid choice.

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

The application displays the expected error message, as shown in Figure 7-7. Any application you create should be able to detect errors and incorrect inputs. Chapter 9 shows you how to handle errors so that they’re user friendly.

 

 

 

 

 

 

 

 

 

Figure 7-6: Menus let you choose one option from a list of

options.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 7-7:

Every application you create

should include some means of detecting errant input.

 

 

 

 

 

 

Using Nested Decision Statements

The decision-making process often happens in levels. For example, when you go to the restaurant and choose eggs for breakfast, you have made a first-level decision. Now the server asks you what type of toast you want with your eggs. The server wouldn’t ask this question if you had ordered pancakes, so the selection of toast becomes a second-level decision. When

the breakfast arrives, you decide whether you want to use jelly on your toast. This is a third-level decision. If you had selected a kind of toast that doesn’t work well with jelly, you might not have had to make this decision at all. This process of making decisions in levels, with each level reliant on the decision made at the previous level, is called nesting. Developers often use nesting techniques to create applications that can make complex decisions based on various inputs. The following sections describe several kinds of nesting you can use within Python to make complex decisions.

 

 

Using multiple if or if…else statements

The most commonly used multiple selection technique is a combination of if and if…else statements. This form of selection is often called a selection tree because of its resemblance to the branches of a tree. In this case, you follow a particular path to obtain a desired result. The example in this section also appears with the downloadable source code as MultipleIfElse.py.

 

  1. Open a Python File

You see an editor where you can type the example code.

2y.peT the following code into the window — pressing Enter after each line:

 

This is simply an extension of the IfElse.py example you see in the “Using the if…else statement in an application” section of the chapter. However, notice that the indentation is different. The second if… else statement is indented within the first if…else statement. The indentation tells Python that this is a second-level statement.

 

 

  1. Choose RunRun

You see a Python Shell window open with a prompt to type a number between 1 and 10.

  1. Type 5 and press Enter.

The shell asks for another number between 1 and 10.

  1. Type 2 and press Enter.

You see the combination of the two numbers as output, as shown in Figure 7-8.

 

 

 

 

 

Figure 7-8: Adding mul­ tiple levels lets you per­ form tasks with greater complexity.

 

 

This example has the same input features as the IfElse.py example. For example, if you attempt to provide a value that’s outside the requested range, you see an error message. The error message is tailored for either the first or second input value so that the user knows which value was incorrect.

 

Providing specific error messages is always useful because users tend to become confused and frustrated otherwise. In addition, a specific error mes- sage helps you find errors in your application much faster.

 

 

Combining other types of decisions

It’s possible to use any combination of if, if…else, and if…elif state- ments to produce a desired outcome. You can nest the code blocks as many levels deep as needed to perform the required checks. For example, Listing 7-1 shows what you might accomplish for a breakfast menu. This example also appears with the downloadable source code as MultipleIfElif.py.

 

 

Listing 7-1:    Creating a Breakfast Menu

print(“1. Eggs”) print(“2. Pancakes”) print(“3. Waffles”) print(“4. Oatmeal”)

MainChoice = int(input(“Choose a breakfast item: “))

 

if (MainChoice == 2): Meal = “Pancakes”

elif (MainChoice == 3): Meal = “Waffles”

 

if (MainChoice == 1): print(“1. Wheat Toast”) print(“2. Sour Dough”) print(“3. Rye Toast”) print(“4. Pancakes”)

Bread = int(input(“Choose a type of bread: “))

 

if (Bread == 1):

print(“You chose eggs with wheat toast.”) elif (Bread == 2):

print(“You chose eggs with sour dough.”) elif (Bread == 3):

print(“You chose eggs with rye toast.”) elif (Bread == 4):

print(“You chose eggs with pancakes.”) else:

print(“We have eggs, but not that kind of bread.”)

 

elif (MainChoice == 2) or (MainChoice == 3): print(“1. Syrup”)

print(“2. Strawberries”) print(“3. Powdered Sugar”)

Topping = int(input(“Choose a topping: “))

 

if (Topping == 1):

print (“You chose ” + Meal + ” with syrup.”) elif (Topping == 2):

print (“You chose ” + Meal + ” with strawberries.”) elif (Topping == 3):

print (“You chose ” + Meal + ” with powdered sugar.”)

else:

print (“We have ” + Meal + “, but not that topping.”)

 

elif (MainChoice == 4): print(“You chose oatmeal.”)

 

else:

print(“We don’t serve that breakfast item!”)

 

 

This example has some interesting features. For one thing, you might assume that an if…elif statement always requires an else clause. This example shows a situation that doesn’t require such a clause. You use an if…elif statement to ensure that Meal contains the correct value, but you have no other options to consider.

 

The selection technique is the same as you saw for the previous examples.  A user enters a number in the correct range to obtain a desired result. Three of the selections require a secondary choice, so you see the menu for that choice. For example, when ordering eggs, it isn’t necessary to choose a top- ping, but you do want a topping for pancakes or waffles.

 

Notice that this example also combines variables and text in a specific way. Because a topping can apply equally to waffles or pancakes, you need some method for defining precisely which meal is being served as part of the output. The Meal variable that the application defines earlier is used as part of the output after the topping choice is made.

 

The best way to understand this example is to play with it. Try various menu combinations to see how the application works. For example, Figure 7-9 shows what happens when you choose a waffle breakfast with a strawberry topping.

 

 

 

 

 

 

 

 

 

 

 

 

Figure 7-9: Many appli­ cations rely on multilevel

menus.