What is DECISION MAKING: THE IF STATEMENT AND COMPARISON OPERATORS IN PYTHON PROGRAMMING

DECISION MAKING: THE IF STATEMENT AND COMPARISON OPERATORS

A condition is a Boolean expression with the value True or False. The following determines whether 7 is greater than 4 and whether 7 is less than 4: 

In [1]: 7 > 4
Out[1]: True
In [2]: 7 < 4
Out[2]: False

True and False are Python keywords. Using a keyword as an identifier causes a Syntax­Error. True and False are each capitalized.
Operators >, <, >= and <= all have the same precedence. Operators == and != both have the same precedence, which is lower than that of >, <, >= and <=. A syntax error occurs when any of the operators ==, !=, >= and <= contains spaces between its pair of symbols:

In [3]: 7 > = 4
File "<ipython-­input­-3­-5c6e2897f3b3>", line 1
7 > = 4
^
SyntaxError: invalid syntax

Another syntax error occurs if you reverse the symbols in the operators !=, >= and <= (by writing them as =!, => and =<).

Making Decisions with the if Statement: Introducing Scripts

We now present a simple version of the if statement, which uses a condition to decide whether to execute a statement (or a group of statements). Here we’ll read two integers from the user and compare them using six consecutive if statements, one for each comparison operator. If the condition in a given if statement is True, the corresponding print statement executes; otherwise, it’s skipped.

IPython interactive mode is helpful for executing brief code snippets and seeing immediate results. When you have many statements to execute as a group, you typically write them as a script stored in a file with the .py (short for Python) extension—such as fig02_01.py for this example’s script. Scripts are also called programs. For instructions on locating and executing the scripts in this article, see Chapter 1’s IPython Test­Drive.

Each time you execute this script, three of the six conditions are True. To show this, we execute the script three times—once with the first integer less than the second, once with the same value for both integers and once with the first integer greater than the second. The three sample executions appear after the script Each time we present a script like the one below, we introduce it before the figure, then explain the script’s code after the figure. We show line numbers for your convenience—these are not part of Python. IDEs enable you to choose whether to display line numbers. To run this example, change to this chapter’s ch02 examples folder, then enter:

ipython fig02_01.py

or, if you’re in IPython already, you can use the command:

run fig02_01.py

1 # fig02_01.py
2 """Comparing integers using if statements and comparison operators."""
3
4 print('Enter two integers, and I will tell you',
5 'the relationships they satisfy.')
6
7 # read first integer
8 number1 = int(input('Enter first integer: '))
9
10 # read second integer
11 number2 = int(input('Enter second integer: '))
12
13 if number1 == number2:
14 print(number1, 'is equal to', number2)
15
16 if number1 != number2:
17 print(number1, 'is not equal to', number2)
18
19 if number1 < number2:
20 print(number1, 'is less than', number2)
21
22 if number1 > number2:
23 print(number1, 'is greater than', number2)
24
25 if number1 <= number2:
26 print(number1, 'is less than or equal to', number2)
27
28 if number1 >= number2:
29 print(number1, 'is greater than or equal to', number2)

Enter two integers and I will tell you the relationships they satisfy.
Enter first integer: 37
Enter second integer: 42
37 is not equal to 42
37 is less than 42
37 is less than or equal to 42

Enter two integers and I will tell you the relationships they satisfy.
Enter first integer: 7
Enter second integer: 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7

Enter two integers and I will tell you the relationships they satisfy.
Enter first integer: 54
Enter second integer: 17
54 is not equal to 17
54 is greater than 17
54 is greater than or equal to 17

Comments

Line 1 begins with the hash character (#), which indicates that the rest of the line is a comment:

# fig02_01.py

For easy reference, we begin each script with a comment indicating the script’s file name. A comment also can begin to the right of the code on a given line and continue until the end of that line.

Docstrings

The Style Guide for Python Code states that each script should start with a docstring that explains the script’s purpose, such as the one in line 2:

"""Comparing integers using if statements and comparison operators."""

For more complex scripts, the docstring often spans many lines. In later chapters, you’ll use docstrings to describe script components you define, such as new functions and new types called classes. We’ll also discuss how to access docstrings with the IPython help mechanism.

Blank Lines

Line 3 is a blank line. You use blank lines and space characters to make code easier to read. Together, blank lines, space characters and tab characters are known as white space. Python ignores most white space—you’ll see that some indentation is required.

Splitting a Lengthy Statement Across Lines

Lines 4–5

print('Enter two integers, and I will tell you',
'the relationships they satisfy.')

display instructions to the user. These are too long to fit on one line, so we broke them into two strings. Recall that you can display several values by passing to print a comma­separated list—print separates each value from the next with a space.

Typically, you write statements on one line. You may spread a lengthy statement over several lines with the \ continuation character. Python also allows you to split long code lines in parentheses without using continuation characters (as in lines 4–5). This is the preferred way to break long code lines according to the Style Guide for Python Code. Always choose breaking points that make sense, such as after a comma in the preceding call to print or before an operator in a lengthy expression.

Reading Integer Values from the User

Next, lines 8 and 11 use the built­in input and int functions to prompt for and read two integer values from the user.

if Statements

The if statement in lines 13–14

if number1 == number2:
print(number1, 'is equal to', number2)

uses the == comparison operator to determine whether the values of variables number1 and number2 are equal. If so, the condition is True, and line 14 displays a line of text indicating that the values are equal. If any of the remaining if statements’ conditions are True (lines 16, 19, 22, 25 and 28), the corresponding print displays a line of text.

Each if statement consists of the keyword if, the condition to test, and a colon (:) followed by an indented body called a suite. Each suite must contain one or more statements. Forgetting the colon (:) after the condition is a common syntax error.

Suite Indentation

Python requires you to indent the statements in suites. The Style Guide for Python Code recommends four­space indents—we use that convention throughout this article.

You’ll see in the next chapter that incorrect indentation can cause errors.

Confusing == and =

Using the assignment symbol (=) instead of the equality operator (==) in an if statement’s condition is a common syntax error. To help avoid this, read == as “is equal to” and = as “is assigned.” You’ll see in the next chapter that using == in place of = in an assignment statement can lead to subtle problems.

Chaining Comparisons

You can chain comparisons to check whether a value is in a range. The following comparison determines whether x is in the range 1 through 5, inclusive:

In [1]: x = 3
In [2]: 1 <= x <= 5
Out[2]: True
In [3]: x = 10
In [4]: 1 <= x <= 5
Out[4]: False

*

Post a Comment (0)
Previous Post Next Post