Table of Contents » Chapter 3 : Processing : Decisions : if Statements
if Statements
Contents
Overview
The most fundamental decision construct we have in Python is the if statement, which will execute a block (one or more lines) of code if a specified condition evaluates to True. In English, we could describe this concept as "if this specific thing is true, then do the following." As an example, "if your score is 100, then print 'Perfect!'" In Python code, we would write this as:
if score == 100:
print("Perfect!")
There are some new syntactic details to consider in this code (which we will address below) but, for now, pay more attention to the concept of "if this then do that." Keeping this in mind i sthe start of constructing decisions in Python.
The general form of the if statement looks like this:
if condition:
code_block
The first key details to notice about this general form are the following:
- The if keyword which indicates to Python that it must evaluate an expression (condition) in order to make a decision.
- The condition that follows the if keyword is the expression that must evaluate to True in order for the code block to be run. If the condition evaluates to False, the code block will be skipped, it will not run, and program execution continues with any code that appears on the next non-indented line below the code block.
- The colon (:) at the end of the if statement line is a required syntactic element that indicates the end of the if statement and the beginning of the code block on the next line.
- The indentation of the code block is a requirement in Python that indicates what line(s) of code are included in the code block.
- The code block is from one to many lines of code that will run if the condition evaluates to True.
Figure 1 depicts the general form of the if statement as a flow chart. The execution flow represents the flow of the program up to the point of the if condition. When the if condition is evaluated by the interpreter, the result will be either True or False. If the result is True then execution flow moves into the code_block and that code runs. When it is finished flow continues to the next statement after the indented code_block. If, however, the if condition returns False, then the code_block is skipped and execution flow continues to the next statement after the indented code_block. Let's take a look at an example:
low = 1
high = 10
secret_number = 8
print("Program started.")
guess = int(input("Enter your guess between " + str(low) + " and " + str(high) + ": "))
if guess == secret_number:
print("You guessed right!")
print("Program complete.")
And running the program looks like this:
Program started.
Enter your guess between 1 and 10: 8
You guessed right!
Program complete.

Notes:
- In this example, I included an initial print statement to display the start of the program to depict the execution flow.
- The user prompt collects a number from the user. Remember that anything entered at a user prompt defaults to a string, so I used the int() function to convert it to an integer.
- The if statement uses the double-equal comparison operator (==) to compare the user-entered guess with the secret_number.
- A common mistake in code like this is to use a single-equal symbol instead of the double-equal symbol. See the full list of comparison operators below for more information.
- Note that the print statement on line 7 is indented, in Python this is how we indicate what lines of code are part of the code_block "inside" of the decision statement (as indicated on the flowchart above).
- The last line is not indented, which means it is not part of the code_block inside of the decision statement.
In the example above we used the double-equal comparison symbol in our if statement condition. That symbol is one of the numerous comparison operators that exist in Python. Here is a list of all of them:
Operator | Comparison | Description |
---|---|---|
== | Equal |
The double-equal symbol compares the value with the value. If they are equal, then it results in True. If the comparison is not equal, then it results in False. Note: A common mistake in coding is to use the single-equal sign (=) instead of the double-equal (==). This mistake can cause significant problems because instead of making a comparison, the single-equal assigns the values of the right side to the left side. Example:
Condition Result: False
|
!= | Not Equal |
This comparison operator is the opposite of the equal operator above. It compares the value with the value. If they are not equal, then it results in True. If the comparison is equal, then it results in False.
Example:
Condition Result: True
|
> | Greater Than |
This comparison operator checks if the value is greater than (determined by the data type) the value. If the is greater, then it results in True. If the is not greater than the right side, then it results in False.
Example:
Condition Result: False
|
< | Less Than |
This comparison operator checks if the value is less than (determined by the data type) the value. If the is less, then it results in True. If the is not less than the right side, then it results in False.
Example:
Condition Result: True
|
>= | Greater Than or Equal To |
This comparison operator checks if the value is greater or equal to (determined by the data type) the value. If the is greater or equal to, then it results in True. If the is not greater or equal to than the right side, then it results in False.
Example:
Condition Result: False
|
<= | Less Than or Equal To |
This comparison operator checks if the value is less than or equal to (determined by the data type) the value. If the is less than or equal to, then it results in True. If the is not less than or equal to the right side, then it results in False.
Example:
Condition Result: True
|
The if statement examples provided above contain a single condition (x == y for example), however, our conditions can be more complex and make several comparisons in one compound condition. To create more complex conditions, we need a way to connect more than one condition together, which we do with logical operators. Here is a list of the logical operators in Python:
Logical Operators
Operator | Description |
---|---|
and |
The and operator compares the condition to its left with the condition to its right, if both conditions are True then the compound condition is True. If either of the two conditions or both, are False, then the compound condition is False.
Examples:
Condition Result: True
Condition Result: False
Condition Result: True
|
or |
The or operator compares the condition to its left with the condition to its right, if either of the conditions is True then the compound condition is True. In a compound condition when more than two conditions, each separated by an or, as long as any one of the conditions is True then the compound condition is True.
Examples:
Condition Result: True (both are True)
Condition Result: True (the first condition is True)
Condition Result: True (at least one condition is True)
|
not |
The not operator reverses the result of the compound condition, so if the compound returns True the not operator will reverse it to False, and if the compound condition returns False the not operator will reverse it to True. In the examples below, notice that the compound condition is placed inside parenthesis and the not operator precedes that set of parenthesis.
Examples:
Condition Result: False
Condition Result: False
Condition Result: False
|
Problem 1
if Statement w/Compound Condition: Write a Python program that prompts the user for their age. If their age is between 40 and 50 inclusive, print "You are middle-aged."
Please enter your age: 43
You are middle-aged.
The if statement works well when we have a single decision to make. That decision can be a single condition or a compound condition. However, the simple if only executes code if the condition result is True. We often need one code_block if the result is True and a different block of code if the result is False. To accomplish this, we will learn the if-else statement on the next page.