The Idea of If Statements

A box labelled "IF ___" has two arrows coming out. One arrow points to a box labelled "THEN do A" and another arrow points to another box labelled "THEN do B". Both of those boxes have arrows that converge on a fourth box labelled "Continue...".

If an expression is true, then take some action. Otherwise, don’t take that action. Either way, execution continues afterwards. That’s the core idea of an if statement.

Purpose

Three lines of text with pictures. The first line reads "IF" followed by a raining cloud. The second line reads "THEN bring" followed by an umbrella. The third line reads "OTHERWISE do not."

if statements make code smarter. They let you do different things in different situations. In this example, we decide to bring an umbrella or not based on whether it is raining. That’s a simple but logical decision that we can make.

Syntax

An `if` statement is shown, with the components labelled as "if keyword", "conditional", "colon", "indentation", and "body".

There are four parts to an if statement. First, you have the keyword if. Then, you have the conditional expression. The conditional is followed by a colon. These first three parts together are called the header. Finally, you have the body of the if statement.

Conditionals

if age > 21:
    pass

if "cat" in animal_name:
    pass

if rent > 2000 and rooms < 2:
    pass

if not on_fire():
    pass

You already learned about writing conditionals. Conditional expressions can be variables, comparisons, function calls, or combinations using and, or, and not. In the code shown here, you can see quite a few different kinds of valid conditional expressions.

Body

income = int(input("Your income?"))

if income > 2000:
    # Body starts here, indented
    tax = .8
    adjusted = income * tax
    print("Income:", adjusted)
    # Body ends here

print("This line is not in the body!")

The body of an if statement is a sequence of one or more statements. This body must be indented with 4 spaces. Anything indented below the if keyword is said to be “inside” the if statement. These indented statements will be executed if the conditional evaluates to True. Otherwise, Python will skip right over those lines of code, as the last line here shows.

The “Else” Block

precipitation = 0

if precipitation > 0:
    print("It is raining")
else:
    print("It is NOT raining")

if statements can optionally have an else body. If the conditional evaluates to False, then the else will be executed instead of the if body. The if body will be skipped over as if its lines of code did not exist. Only one of the two bodies will ever be executed! Note the colon after the word else, and that it has its own body.

Branching

A program with two `if` statements is shown. In both `if` statements, two lines extend from the top of the control structure down to the bottom. In the first block, one of the lines goes straight down, while the other curves inward to follow the indentation. In the second block, one of the lines goes to the first indented area, while the second line moves down to the second indented area; both lines converge back to the final point. These demonstrate how the program might skip over or go through the body.

Think about your program as a flowing stream. Normally it will go from top to bottom. An if statement changes that flow to optionally go around. We call that behavior branching. Every time you have another if statement, you have another two branches. This also happens if you have an else statement.

Trace Tables

A program is shown on the left, with a trace table on the right showing off its values.

Last chapter, we learned how you can make a trace table that follows the execution of a program. We now must add an extra column to this table, to differentiate between steps and lines. With if statements, it is possible that a step may skip a line of code. Even though the program shown here has 6 lines of actual code, it only has 4 steps! Notice that on lines with if statements, we still have a step, but we simply repeat the values unchanged, since the values are only read, not written.

Possible Initialization Problem

# Current hour of day
hour = 7

if hour > 6:
    time = "It is daylight"

# This will cause an error!
# Did not initialize time on both branches
print(time)

Keep in mind that if statements allow us to potentially skip lines of code. We have previously seen that we must be careful to write variables before we read them. If we initialize a variable in one branch, then we must initialize that variable in the other branch. Or, we should have already initialized the variable earlier in the program and now only update the variable.

Summary