Skip to main content

Section 23.2 The if Statement

In Python, we test data and execute instructions if the test is true using an if statement which takes the form:
if TEST:
The test, also known as the condition, must be a logical expression - something that evaluates to either True or False. Like a while statement, after the test, we must type a colon (:) and then indent the lines of the body - the instructions to execute if the test is True.
While learning about while, we already learned the most common way to write logical expressions - by using comparison operators. As a review, here they are - the result of using any of these is either True or False:
Table 23.2.1.
Expression Logical meaning
a < b True if a is less than b
a <= b True if a is less than or equal to b
a > b True if a is greater than b
a >= b True if a is greater than or equal to b
a == b True if a is equal to b. (Two equals signs, to distinguish it from assignment)
a != b True if a is not equal to b.
Unlike a while, an if will only run the instructions in its body one time. After the instructions have been executed (which only happens if the test was True), Python continues running the rest of this program. If the test isn’t True (is False) then execution will skip the block following the if and continue with the next statement following the block after the if statement.
Run the program below in codelens. Then change the first line so that it sets x to 4 and again run with codelens to see how the behavior differs if the test is True or False.
The figure below is called a flowchart. It shows the execution paths for a program. The diamond shape contains the logical expression and shows the path that the execution takes if the logical expression is true as well as the path if the logical expression is false. Notice that it will only execute the statements in the indented block if the logical expression is true. Regardless of whether the indented code is executed, the program then continues running.
Figure 23.2.2. Flow of execution for an if statement

Checkpoint 23.2.3.

    Given the code below, what will be printed?
    x = 10
    if x >= 8:
        print ("A")
    print ("B")
  • A
  • A will be printed, but then the program continues running
  • B
  • 10 is "greater than or equal to" 8
  • A and B
  • Correct
  • Nothing
  • Try modifying the program above so you can test this code.
You have attempted of activities on this page.