Skip to content

Making Simple Decisions Using the if Statement

Making Simple Decisions Using the if Statement

The if statement is the easiest method for making a decision in Python. It simply states that if something is true, Python should perform the steps that follow. The following sections tell you how you can use the if statement to make decisions of various sorts in Python. You may be surprised at what this simple statement can do for you.

 

 

Understanding the if statement

You use if statements regularly in everyday life. For example, you may say to yourself, “If it’s Wednesday, I’ll eat tuna salad for lunch.” The Python if state- ment is a little less verbose, but it follows precisely the same pattern. Say you create a variable, TestMe, and place a value of 6 in it, like this:

 

 

You can then ask the computer to check for a value of 6 in TestMe, like this:

 

 

Every Python if statement begins, oddly enough, with the word if. When Python sees if, it knows that you want it to make a decision. After the word if comes a condition. A condition simply states what sort of comparison you want Python to make. In this case, you want Python to determine whether TestMe contains the value 6.

 

Notice that the condition uses the relational equality operator, ==, and not the assignment operator, =. A common mistake that developers make is to use the assignment operator rather than the equality operator. You can see a list of relational operators in Chapter 6.

 

The condition always ends with a colon (:). If you don’t provide a colon, Python doesn’t know that the condition has ended and will continue to look for additional conditions on which to base its decision. After the colon come any tasks you want Python to perform. In this case, Python prints a state- ment saying that TestMe is equal to 6.

 

 

Using the if statement in an application

It’s possible to use the if statement in a number of ways in Python. However, you immediately need to know about three common ways to use it:

 

  • Use a single condition to execute a single statement when the condition is
  • Use a single condition to execute multiple statements when the condi- tion is
  • Combine multiple conditions into a single decision and execute one or more statements when the combined condition is

 

The following sections explore these three possibilities and provide you  with examples of their use. You see additional examples of how to use the  if statement throughout the book because it’s such an important method of making decisions.

 

Working with relational operators

A relational operator determines how a value on the left side of an expres- sion compares to the value on the right side of an expression. After it makes the determination, it outputs a value of true or false that reflects the truth value of the expression. For example, 6 == 6 is true, while 5 == 6 is false. Table 6-3 contains a listing of the relational operators. The follow- ing steps show how to create and use an if statement. This example also appears with the downloadable source code as SimpleIf1.py.

 

  1. Open a Python Shell

You see the familiar Python prompt.

  1. Type TestMe = 6 and press Enter.

This step assigns a value of 6 to TestMe. Notice that it uses the assign- ment operator and not the equality operator.

  1. Type if TestMe == 6: and press Enter.

This step creates an if statement that tests the value of TestMe using the equality operator. You should notice two features of the Python Shell at this point:

  • The word if is highlighted in a different color than the rest of the
  • The next line is automatically

 

 

  1. Type print(“TestMe does equal 6!”) and press Enter.

Notice that Python doesn’t execute the if statement yet. It does indent the next line. The word print appears in a special color because it’s a function name. In addition, the text appears in another color to show you that it’s a string value. Color coding makes it much easier to see how Python works.

5es. sPErnter.

The Python Shell outdents this next line and executes the if statement, as shown in Figure 7-1. Notice that the output is in yet another color. Because TestMe contains a value of 6, the if statement works as expected.

 

 

 

Figure 7-1: Simple if statements can help your appli­ cation know what to do in certain conditions.

 

 

Performing multiple tasks

Sometimes you want to perform more than one task after making a decision. Python relies on indentation to determine when to stop executing tasks as part of an if statement. As long as the next line is indented, it’s part of the if statement. When the next line is outdented, it becomes the first line of code outside the if block. A code block consists of a statement and the tasks associated with that statement. The same term is used no matter what kind of statement you’re working with, but in this case, you’re working with an if statement that is part of a code block. This example also appears with the downloadable source code as SimpleIf2.py.

 

  1. Open a Python Shell window.

You see the familiar Python prompt.

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

 

 

 

Notice that the shell continues to indent lines as long as you continue to type code. Each line you type is part of the current if statement code block.

When working in the shell, you create a block by typing one line of code after another. If you press Enter twice in a row without entering any text, the code block is ended, and Python executes the entire code block at one time.

3es. sPErnter.

Python executes the entire code block. You see the output shown in Figure 7-2.

 

 

 

 

 

Figure 7-2:

A code block can contain mul­ tiple lines of code — one

for each

task.

 

 

Making multiple comparisons using logical operators

So far, the examples have all shown a single comparison. Real life often requires that you make multiple comparisons to account for multiple require- ments. For example, when baking cookies, if the timer has gone off and the edges are brown, it’s time to take the cookies out of the oven.

 

In order to make multiple comparisons, you create multiple conditions using relational operators and combine them using logical operators (see Table 6-4). A logical operator describes how to combine conditions. For example, you might say x == 6 and y == 7 as two conditions for performing one or more tasks. The and keyword is a logical operator that states that both conditions must be true.

 

One of the most common uses for making multiple comparisons to deter- mine when a value is within a certain range. In fact, range checking, the act of determining whether data is between two values, is an important part of making your application secure and user friendly. The following steps help

 

 

you see how to perform this task. In this case, you create a file so that you can run the application multiple times. This example also appears with the downloadable source code as SimpleIf3.py.

 

  1. Open a Python File window.

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 obtaining an input value. You have no idea what the user has typed other than that it’s a value of some sort. The use

of the int() function means that the user must type a whole number (one without a decimal portion). Otherwise, the application will raise an exception (an error indication; Chapter 9 describes exceptions). This first check ensures that the input is at least of the correct type.

The if statement contains two conditions. The first states that Value must be greater than 0. You could also present this condition as  Value >= 1. The second condition states that Value must be less than or equal to 10. Only when Value meets both of these conditions will the if statement succeed and print the value the user typed.

  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 in Figure 7-3.

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

The application doesn’t output anything because the number is in the wrong range. Whenever you type a value that’s outside the programmed range, the statements that are part of the if block aren’t executed.

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

Python displays the error message shown in Figure 7-4. Even though you may think of 5.5 and 5 as both being numbers, Python sees the first number as a floating-point value and the second as an integer.

 

 

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

Python displays about the same error message as before. Python doesn’t differentiate between types of wrong input. It only knows that the input type is incorrect and therefore unusable.

 

 

 

 

Figure 7-3: The applica­ tion verifies the value is in the right range and outputs a message.

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 7-4: Typing the wrong type of informa­ tion results in an error message.

 

 

The best applications use various kinds of range checking to ensure that the application behaves in a predictable manner. The more predictable an appli- cation becomes, the less the user thinks about the application and the more time the user spends on performing useful work. Productive users tend to be a lot happier than those who constantly fight with their applications.