Common Programming Error

Failure to indent all statements that belong to an if suite or an else suite results in a syntax error.

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 rectangles (for actions) and diamonds (for decisions). We continue to emphasize this action/decision 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 8089, 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 if/else double-selection structure flowchart.

76 Control Structures

This pseudocode can be written in Python as if grade >= 90:

print "A" else:

print "B" else:

print "C" else:

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.

+1 0

Responses

  • asmeret
    What is the Algorithm of if student grade is greater than or equal to 90 print "A"?
    6 years ago

Post a comment