3.5 if Statement

Suppose that a passing grade on an examination is 60. The pseudocode

If student’s grade is greater than or equal to 60
        Display 'Passed'

determines whether the condition “student’s grade is greater than or equal to 60” is true or false. If the condition is true, 'Passed' is displayed. Then, the next pseudocode statement in order is “performed.” (Remember that pseudocode is not a real programming language.) If the condition is false, nothing is displayed, and the next pseudocode statement is “performed.” The pseudocode’s second line is indented. Python code requires indentation. Here it emphasizes that 'Passed' is displayed only if the condition is true.

Let’s assign 85 to the variable grade, then show and execute the Python if statement for the pseudocode:

In [1]: grade = 85

In [2]: if grade >= 60:
   ...:     print('Passed')
   ...:
Passed

The if statement closely resembles the pseudocode. The condition grade >= 60 is True, so the indented print statement displays 'Passed'.

Suite Indentation

Indenting a suite is required; otherwise, an IndentationError syntax error occurs:

In [3]: if grade >= 60:
   ...: print('Passed') # statement is not indented properly
  File "<ipython-input-3-f42783904220>", line 2
    print('Passed') # statement is not indented properly
        ^
IndentationError: expected an indented block

An IndentationError also occurs if you have more than one statement in a suite and those statements do not have the same indentation:

In [4]: if grade >= 60:
   ...: print('Passed')   # indented 4 spaces
   ...: print('Good job!) # incorrectly indented only two spaces
  File <ipython-input-4-8c0d75c127bf>, line 3
    print('Good job!) # incorrectly indented only two spaces
    ^
IndentationError: unindent does not match any outer indentation level

Sometimes error messages may not be clear. The fact that Python calls attention to the line is usually enough for you to figure out what’s wrong. Apply indentation conventions uniformly throughout your code. Programs that are not uniformly indented are hard to read.

if Statement Flowchart

The flowchart for the if statement in snippet [2] is:

A diagram of an If Flow chart with circles, arrows, diamonds and rectangles.

The decision (diamond) symbol contains 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 condition in the symbol is True. This points to the action (or group of actions) that should execute.

  • The other indicates the direction to follow when the condition is False. This skips the action (or group of actions).

Every Expression Can Be Interpreted as Either True or False

You can base decisions on any expression. A nonzero value is True. Zero is False:

In [5]: if 1:
   ...:     print('Nonzero values are true, so this will print')
   ...:
Nonzero values are true, so this will print

In [6]: if 0:
   ...:     print('Zero is false, so this will not print')

In [7]:

Strings containing characters are True and empty strings ('', "" or """""") are False.

An Additional Note on Confusing == and =

Using the equality operator == instead of the assignment symbol = in an assignment statement can lead to subtle problems. For example, in this session, snippet [1] defined grade with the assignment:

grade = 85

If instead we accidentally wrote:

grade == 85

then grade would be undefined and we’d get a NameError.

If grade had been defined before the preceding statement, then grade == 85 would evaluate to True or False, depending on grade’s value, and not perform the intended assignment. This is a logic error.

tick mark Self Check

  1. (True/False) If you indent a suite’s statements, you will not get an IndentationError.
    Answer: False. All the statements in a suite must have the same indentation. Otherwise, an IndentationError occurs.

  2. (IPython Session) Redo this section’s snippets [1] and [2], then change grade to 55 and repeat the if statement to show that its suite does not execute. The next section shows how to recall and re-execute earlier snippets to avoid having to re-enter the code.
    Answer:

    In [1]: grade = 85
    
    In [2]: if grade >= 60:
       ...:     print('Passed')
       ...:
    Passed
    
    In [3]: grade = 55
    
    In [4]: if grade >= 60:
       ...:     print('Passed')
       ...:
    
    In [5]: