Outline 3.1 Introduction
3.5 if Selection Structure
Selection structures choose among alternative courses of action. For example, suppose that the passing grade on an examination is 60. Then the pseudocode statement
If student’s grade is greater than or equal to 60 Print “Passed”
determines whether the condition “student’s grade is greater than or equal to 60” is true or false. If the condition is true, then “Passed” is printed, and the next pseudocode statement in order is “performed.” (Remember that pseudocode is not a real programming language.) If the condition is false, the print statement is ignored, and the next pseudocode statement is performed. Note that the second line of this selection structure is indented. Such inden- tation is optional (for pseudocode), but it is highly recommended because indentation em- phasizes the inherent hierarchy of structured programs. When we convert pseudocode into Python code, indentation is required.
The preceding pseudocode if statement may be written in Python as if grade >= 60:
print "Passed"
Notice that the Python code corresponds closely to the pseudocode. This similarity is the reason that pseudocode is a useful program development tool. The statement in the body of the if structure outputs the character string "Passed".
The flowchart of Fig. 3.3 illustrates the single-selection if structure and the diamond symbol. The decision symbol contains an expression, such as a condition, that can be either true or false. The diamond has two flowlines emerging from it: One indicates the direction to follow when the expression in the symbol is true; the other indicates the direction to follow when the expression is false. We learned, in Chapter 2, Introduction to Python Pro- gramming, that decisions can be based on conditions containing relational or equality oper- ators. Actually, a decision can be based on any expression. For instance, if an expression evaluates to zero, it is treated as false, and if an expression evaluates to nonzero, it is treated as true.
Note that the if structure is a single-entry/single-exit structure. We will soon learn that the flowcharts for the remaining control structures also contain (besides small circle symbols and flowlines) rectangle symbols that indicate the actions to be performed and dia- mond symbols that indicate decisions to be made. This type of flowchart emphasizes the action/decision model of programming.
We can envision six bins, each containing control structures of one of the six types. These control structures are empty—nothing is written in the rectangles or in the diamonds. The pro- grammer’s task, then, is assembling a program from as many of each type of control structure as the algorithm demands, combining those control structures in only two possible ways (stacking or nesting), then filling in the actions and decisions in a manner appropriate for the algorithm. We will discuss the variety of ways in which actions and decisions may be written.
3.6
if/else and if/elif/else
Selection Structures
The if selection structure performs a specified action only when the condition is true; oth- erwise, the action is skipped. The if/else selection structure allows the programmer to specify that a different action is to be performed when a condition is true from an action when a condition is false. For example, the pseudocode statement
If student’s grade is greater than or equal to 60 Print “Passed”
else
Print “Failed”
prints Passed if the student’s grade is greater than or equal to 60 and prints Failed if the student’s grade is less than 60. In either case, after printing occurs, the next pseudocode statement in sequence is “performed.” Note that the body of the else is indented. The in- dented body of a control structure is called a suite. Remember that indentation conventions you choose should be applied uniformly throughout programs. It is imperative for Python when it is executing code, and programs that do not obey uniform spacing conventions also are difficult to read.
Good Programming Practice 3.1
If there are several levels of indentation, each suite must be indented. Different suites at the same level do not have to be indented by the same amount, but doing so is good programming
practice. 3.1
The preceding pseudocode if/else structure can be written in Python as if grade >= 60: print "Passed" else: print "Failed" Fig. 3.3 Fig. 3.3 Fig. 3.3
Fig. 3.3
if
single-selection structure flowchart.grade >= 60 true print “Passed”
Common Programming Error 3.2
Failure to indent all statements that belong to an if suite or an else suite results in a syn-
tax error. 3.2
The flowchart of Fig. 3.4 illustrates the flow of control in the if/else structure. Once again, note that (besides small circles and arrows) the symbols in the flowchart are rectan- gles (for actions) and diamonds (for decisions). We continue to emphasize this action/deci- sion model of computing. Imagine again a bin containing empty double-selection structures. The programmer’s job is to assemble these selection structures (by stacking and nesting) with other control structures required by the algorithm and to fill in the rectangles and diamonds with actions and decisions appropriate to the algorithm being implemented. Nested if/else structures test for multiple cases by placing if/else selection structures inside other if/else selection structures. For example, the following pseudocode statement prints A for exam grades greater than or equal to 90, B for grades 80– 89, C for grades 70–79, D for grades 60–69 and F for all other grades.
If student’s grade is greater than or equal to 90 Print “A”
else
If student’s grade is greater than or equal to 80 Print “B”
else
If student’s grade is greater than or equal to 70 Print “C”
else
If student’s grade is greater than or equal to 60 Print “D” else Print “F” Fig. 3.4 Fig. 3.4 Fig. 3.4
Fig. 3.4
if
/else
double-selection structure flowchart. grade >= 60print “Failed” print “Passed”
true false
This pseudocode can be written in Python as if grade >= 90: print "A" else: if grade >= 80: print "B" else: if grade >= 70: print "C" else: if grade >= 60: print "D" else: print "F"
If grade is greater than or equal to 90, the first four conditions are met, but only the
print statement after the first test executes. After that print executes, the else part of the “outer” if/else statement skips.
Performance Tip 3.1
A nested if/else structure is faster than a series of single-selection if structures because the testing of conditions terminates after one of the conditions is satisfied. 3.1 Performance Tip 3.2
In a nested if/else structure, place the conditions that are more likely to be true at the be- ginning of the nested if/else structure. This enables the nested if/else structure to run faster and exit earlier than an equivalent if/else structure in which infrequent cases ap-
pear first. 3.2
Many Python programmers prefer to write the preceding if structure as if grade >= 90: print "A" elif grade >= 80: print "B" elif grade >= 70: print "C" elif grade >= 60: print "D" else: print "F"
thus replacing the double-selection if/else structure with the multiple-selection if/elif/
else structure. The two forms are equivalent. The latter form is popular because it avoids the deep indentation of the code to the right. Such indentation often leaves little room on a line, forcing lines to be split over multiple lines and decreasing program readability.
Each elif can have one or more actions. The flowchart in Fig. 3.5 shows the general
if/elif/else multiple-selection structure. The flowchart indicates that, after an if or
elif statement executes, control immediately exits the if/elif/else structure. Again, note that (besides small circles and arrows) the flowchart contains rectangle symbols and diamond symbols. Imagine that the programmer has access to a deep bin of empty if/
other control structures to form a structured implementation of an algorithm’s flow of con- trol. The rectangles and diamonds are then filled with actions and decisions appropriate to the algorithm.
The else statement of the if/elif/else structure is optional. However, most pro- grammers include an else statement at the end of a series of elif statements to handle any condition that does not match the conditions specified in the elif statements. We call the condition handled by the else statement the default condition. If an if/elif struc- ture specifies an else statement, it must be the last statement in the structure.
Good Programming Practice 3.2
Provide a default condition in if/elif structures. Conditions not explicitly tested in an if/ elif structure without a default condition are ignored. Including a default condition focus- es the programmer on the need to process exceptional conditions. 3.2 Software Engineering Observation 3.3
A suite can be placed anywhere in a program that a single statement can be placed. 3.3
The if selection structure can contain several statements in its body (suite), and all these statements must be indented. The following example includes a suite in the else part of an if/else structure that contains two statements. A suite that contains more than one statement is sometimes called a compound statement.
Fig. 3.5 Fig. 3.5 Fig. 3.5
Fig. 3.5
if
/elif
/else
multiple-selection structure.condition a case a action(s)
. . .
case b action(s)
condition z case z action(s)
default action(s) condition b if statement first elif statement last elif statement else statement false false false true true true
if grade >= 60: print "Passed."
else:
print "Failed."
print "You must take this course again."
In this case, if grade is less than 60, the program executes both statements in the body of the else and prints
Failed.
You must take this course again.
Notice that both statements of the else suite are indented. If the statement print "You must take this course again."
was not indented, the statement executes regardless of whether the grade is less than 60 or not. This is an example of a logic error.
A programmer can introduce two major types of errors into a program: syntax errors and logic errors. A syntax error violates the rules of the programming language. Examples of syntax errors include using a keyword as an identifier or forgetting the colon (:) after an
if statement. The interpreter catches a syntax error and displays an error message. A logic error causes the program to produce unexpected results and may not be caught by the interpreter. A fatal logic error causes a program to fail and terminate prematurely. For fatal errors, Python prints an error message called a traceback and exits. A nonfatal logic error allows a program to continue executing, but produces incorrect results.
Common Programming Error 3.3
Forgetting to indent all the statements in a suite can lead to syntax or logic errors in a pro-
gram. 3.3
The interactive session in Fig. 3.6 attempts to divide two user-entered values and dem- onstrates one syntax error and two logic errors. The syntax error is contained in the line
print value1 +
The + operator needs a right-hand operand, so the interpreter indicates a syntax error. The first logic error is contained in the line
print value1 + value2
The intention of this line is to print the sum of the two user-entered integer values. How- ever, the strings were not converted to integers, thus the statement does not produce the de- sired result. Instead, the statement produces the concatenation of the two strings—formed by linking the two strings together. Notice that the interpreter does not display any messag- es because the statement is legal.
The second logic error occurs in the line
print int( value1 ) / int( value2 )
The program does not check whether the second user-entered value is 0, so the program attempts to divide by zero. Dividing by zero is a fatal logic error.
Common Programming Error 3.4
An attempt to divide by zero causes a fatal logic error. 3.4 Just as multiple statements can be placed anywhere a single statement can be placed, it is possible to have no statements at all, (i.e., empty statements). The empty statement is represented by placing keyword pass where a statement normally resides (Fig. 3.7).
Common Programming Error 3.5
All control structures must contain at least one statement. A control structure that contains
no statements causes a syntax error. 3.5