CHAPTER 6
Making Decisions with if
Statements
Python includes all the tools you need to make decisions easily and effectively in your code. In this chapter, you meet Python’s if
statements, if… else
statements, and if… elif
statements and put them to work in your code. You also learn how to nest if
statements to make complex decisions in your scripts.
Learn the Essentials of if
Statements
Understanding the if
Statement
Understanding the if… else
Statement
Understanding the if… elif
Statement
Understanding the if… elif… else
Statement
Create an if… elif… else
Statement
Learn the Essentials of if
Statements
To make decisions in your code, you use Python’s various types of if
statements. When an if
statement’s condition evaluates to True
, Python runs the code that follows the statement. An if… else
statement runs the if
code when the condition is True
and the else
code when it is False
. An if… elif
statement can evaluate not only the if
condition but also one or more elif
conditions, as needed; you can add an else
statement that runs code when both if
and all elif
conditions evaluate to False
. You can nest if
statements to make complex decisions.
Essential Features of if
Statements
The three main forms of if
statement are plain if
, if… else
, and if… elif
. The if
statement looks like this, with italics indicating placeholders:
if expression1:
code block 1
The if… else
statement looks like this and is illustrated nearby:
if expression1:
code block 1
else:
code block 2
The if… elif
statement looks like this:
if expression1:
code block 1
elif expression2:
code block 3
The following list explains the components of these if
statements:
if
keyword introduces the if
statement.expression1
and expression2
are expressions that evaluate to a Boolean True
value or a Boolean False
value. For example, if x = 10:
evaluates to True
if x
equals 10
but evaluates to False
if x
evaluates to anything other than 10
.:
) follows expression1
or expression2
. This colon is required; Python throws a SyntaxError: expected ':'
error if you omit the colon.:
) follows the else
statement. This colon is required.code block 1
is an indented block containing one or more statements that Python executes after the if
condition evaluates to True
.code block 2
is an indented block containing one or more statements that Python executes after the if
condition evaluates to False
.code block 3
is an indented block containing one or more statements that Python executes after the elif
statement evaluates to True
.
Each code block must be indented; if not, Python returns an IndentationError
error, such as expected an indented block after 'if' statement
. Visual Studio Code and other editors can automatically apply the required indentation for you.
The end of the indentation marks the end of the code block attached to the if
statement. Execution resumes at the next line that does not have the indentation.
You may want to leave a blank line after the end of an if
block to make your code easier to read, but there is no need to do so.
Understanding the if
Statement
When your code needs to make a straightforward decision between taking an action and not taking an action, you can use an if
statement. For example, your code might check the value of a variable to see whether it is 100 or more. If the value is indeed 100 or more, the code would take action by running the if
code block; if the value is less than 100, the code would take no action.
How the if
Statement Works
An if
statement begins with the if
keyword followed by the expression to be evaluated for the condition. The statement ends with a colon. If the expression evaluates to True
, the statements in the code block run.
if expression:
code block
For example, the following if
statement checks whether the value of the variable x
is greater than 10
. If so, the print()
statement runs. The illustration represents the flow of execution.
if x > 10:
print("x is greater than 10.")
When an if
statement’s code block contains only a single statement, you can place that statement on the same line of code as the if
statement. For example, the following if
statement’s code block has only a single statement:
if ampm < 12:
print("Good morning!")
Instead, you can place the code block on the same line:
if ampm < 12: print("Good morning!")
Create an if
Statement
A straightforward if
statement enables you to test a condition and take action if that condition evaluates to True
. For example, your code may need to evaluate input provided by the user and take action if the input is of a certain type. If the condition evaluates to False
, the code takes no action. Execution continues at the line of code after the end of the if
statement.
Create an if
Statement
In Visual Studio Code, create a new script, and then save it.
Type the following statement, which creates a variable named x
and assigns to it the string resulting from prompting the user to enter a number between 1 and 20. Press .
x = input("Enter a number between 1 and 20 (inclusive): ")
Type the following statement, which converts the string x
to an integer and assigns the result back to x
. Press .
x = int(x)
Type the following if
statement, which tests whether x
is greater than 10
. Press .
if x > 10:
Visual Studio Code automatically indents the next line for you to enter the code block.
Type the following statement, which uses the print()
function to display a message, and then press .
print("x is greater than 10.")
Click Run Python File in Terminal ().
The Terminal pane appears.
Type a number greater than 10 and press .
Python displays the message x is greater than 10
.
Click Run Python File in Terminal () again, but this time type a number less than 11, and then press . This time, the condition evaluates to False
, so the code block does not run, and Python does not display the message.
Understanding the if… else
Statement
When your code needs to decide between two paths of action, use an if… else
statement. The if
line contains an expression that evaluates to a Boolean True
or a Boolean False
. If the expression evaluates to True
, Python runs the statements in the code block that follows the if
line. After this code block comes the else
line, followed by the code block containing the statements for Python to run if the expression evaluates to False
.
How the if…else
Statement Works
An if… else
statement begins with the if
keyword followed by the expression to be evaluated for the condition. The statement ends with a colon. If the expression evaluates to True
, the statements in the if
code block run. If the statement evaluates to False
, execution moves to the else
line, and the statements in the else
code block run.
if expression:
code block 1
else:
code block 2
Continuing the previous example, the following if
statement checks whether the value of the variable x
is greater than 10
. If so, the if
code block runs, and the print()
statement displays a message that x is greater than 10; if not, the else
statement’s code block runs, making its print()
statement display a message that x is 10 or less. The nearby illustration shows the flow of execution.
if x > 10:
print("x is greater than 10.")
else:
print("x is 10 or less.")
Create an if… else
Statement
An if… else
statement enables you to test a condition and take one of two courses of action depending on the result. If the condition evaluates to True
, Python runs the statements in the code block that follows the if
line; if the condition evaluates to False
, Python runs the statements in the code block that follows the else
line.
Create an if…. else
Statement
In Visual Studio Code, create a new script, and then save it.
Type the following statement, and then press . This statement creates a variable named x
, prompts the user to enter a number, converts the input string to an integer, and assigns it to x
.
x = int(input("Enter a number between 1 and 20 (inclusive): "))
Type the if
condition, the colon, and the print()
statement, as before. Press .
if x > 10:
print("x is greater than 10.")
Press to remove the indent, type the else
statement and its colon, and then press .
else:
Visual Studio Code applies an indent after the else:
line.
Type the following print()
statement, and then press .
print("x is 10 or less.")
Click Run Python File in Terminal ().
The Terminal pane appears.
Type a number less than 11, and then press .
Python displays the message from the else
block.
Click Run Python File in Terminal () again. This time, type a number 11 or greater, and then press .
Python displays the message from the if
block.
Understanding the if… elif
Statement
When your code needs to evaluate two or more conditions, use an if… elif
statement. After the if
line (which as usual contains an expression that evaluates to a Boolean True
or a Boolean False
) and the if
code block, the if… elif
statement has one or more elif
lines, each of which contains another expression to evaluate. After the if
expression evaluates to False
, Python evaluates the first elif
expression, running its code block if it evaluates to True
or moving along to the next elif
line if it evaluates to False
.
How the if… elif
Statement Works
The if… elif
statement consists of an if
line with an expression to evaluate, ending in a colon; a code block to execute if the expression evaluates to True
; an elif
line, likewise with an expression and ending in a colon; and a code block to evaluate if the elif
expression evaluates to True
. Here is a pseudocode representation:
if expression1:
code block 1
elif expression2:
code block 2
Here is an example, also illustrated nearby:
if x > 10:
print("x is greater than 10.")
elif x < 5:
print("x is less than 5.")
You can add as many elif
statements as you need to test more than two conditions. You can also add an else
statement after the last elif
statement, making an if… elif… else
statement. See the section “Understanding the if… elif… else
Statement,” later in this chapter, for an example.
Create an if… elif
Statement
An if… elif…
statement enables you to test multiple conditions, taking different actions depending on which condition evaluates to True
and taking no action if each condition evaluates to False
. As usual, the if
line is followed by its code block; similarly, each elif
line is followed by its code block.
You can use multiple elif
lines to test more conditions. You must arrange the elif
lines in the appropriate order for testing, because once a condition evaluates to True
, Python executes the following code block and does not test any further conditions.
Create an if… elif
Statement
In Visual Studio Code, create a new script, and then save it.
Copy and paste — or simply retype — the first three lines from the if… else
example you created in the previous section:
x = int(input("Enter a number between 1 and 20 (inclusive): "))
if x > 10:
print("x is greater than 10.")
Press to create a new line, press to delete the indent, and type the following elif
line. Press again.
elif x < 5:
Visual Studio Code automatically indents the next line following the elif
line and its colon.
Type the following statement, which uses the print()
function to display a message about the value of x
, and then press .
print("x is less than 5.")
Click Run Python File in Terminal ().
The Terminal pane appears.
Type a number less than 5 and press .
Python displays the message x is less than 5
.
Understanding the if… elif… else
Statement
An if… elif… else
statement combines the features of the if… elif
statement and the if… else
statement. First, you specify the if
condition and the code to run if it evaluates to True
; second, you specify one or more elif
conditions, each with the code to run if it is True
; and third, you specify the code to run if both the if
statement and each elif
statement evaluates to False
. You can include as many elif
lines as required for all the conditions you need to test.
How the if… elif… else
Statement Works
The if… elif… else
statement consists of an if
line with an expression to evaluate, ending in a colon; a code block to execute if the expression evaluates to True
; one or more elif
lines, each with an expression, ending in a colon, and followed by a code block to evaluate if that elif
expression evaluates to True
; the else
line, also ending in a colon; and the code block to execute in the else
case. Here is a pseudocode representation:
if expression1:
code block 1
elif expression2:
code block 2
[other elif statements]
else:
code block 3
Here is an example, which is illustrated nearby, that uses two elif
lines:
if x > 10:
print("x is greater than 10.")
elif x < 5:
print("x is less than 5.")
elif x == 5:
print("x equals 5.")
else:
print("x is more than 5 but less than 11.")
Create an if… elif… else
Statement
An if… elif… else
statement enables you to test multiple conditions, taking appropriate action if any condition evaluates to True
and taking other action if all the conditions evaluate to False
. The statement begins with an if
line and expression, followed by a code block. Similarly, each elif
line contains an expression and is followed by its code block. Finally, the else
line appears, without an expression but followed by its code block.
You can include multiple elif
lines to test multiple conditions.
Create an if… elif… else
Statement
In Visual Studio Code, create a new script, and then save it.
Copy and paste — or retype, if you prefer — the first five lines from the if… else
example you created in the previous section:
x = int(input("Enter a number between 1 and 20 (inclusive): "))
if x > 10:
print("x is greater than 10.")
elif x < 5:
print("x is less than 5.")
Press to create a new line, press to remove the indent, and then type the following elif
line. Press again.
elif x == 5:
Type the following print()
statement, and then press .
print("x equals 5.")
Press to remove the indent, type the following else
line, and then press .
else:
Type the following statement, which uses the print()
function to display a message. Press .
print("x is more than 5 but less than 11.")
Click Run Python File in Terminal ().
The Terminal pane appears.
Type a number — this example uses 5
— and press .
Python displays the appropriate message.
Understanding Nested if
Statements
When your code needs to make complex decisions, you can nest one or more if
statements inside another if
statement. You can use any type of if
statement — a straightforward if
statement, an if… else
statement, an if… elif
statement, or an if… elif… else
statement — as either the outer if
statement or the nested if
statement, as needed. You may sometimes need to nest further if
statements within your nested if
statements.
How Nested if
Statements Work
To create a nested if
statement, you create the outer if
statement of your preferred type and enter the nested if
statements in the appropriate code block. Here is a pseudocode representation that shows an if… elif
statement nested in an if… elif… else
statement:
if expression1:
if expression2:
code block 1
if expression3:
code block 2
elif expression4:
code block 3
else:
code block 4
Here is a straightforward example of nested if
statements. The outer statement is if… elif… elif… else
, and the if
block contains two nested if
statements.
if n.isalnum():
if n.isalpha():
r = "alphabetical"
if n.isnumeric():
r = "numeric"
elif n.isspace():
r = "space-based"
elif n.isascii():
r = "ASCII text"
else:
r = "a mystery"
This example demonstrates using several string methods on the string stored in the variable n
, which we assume has been created already. The isalnum()
method returns True
if the string contains alphanumeric characters. The isalpha()
method returns True
if the string contains alphabetical characters, while the isnumeric()
method returns True
if the string contains numbers. The isspace()
method returns True
if the string consists of spaces. The isascii()
method returns True
if the string contains ASCII characters.
Create Nested if
Statements
Nested if
statements enable you to make complex decisions in your code. You begin the outer if
statement with an if
line that contains the if
keyword, an expression that evaluates to True
or False
, and a colon. Within the if
code block, an elif
code block, or the else
code block, you nest if
statements, as needed. When Python evaluates that if
condition or elif
condition as true, or when it reaches the else
line, Python evaluates the nested if
statements and continues executing code accordingly.
Create Nested if
Statements
In Visual Studio Code, create a new script, and then save it.
Note: Press at the end of each line.
Type the following statement, which uses the input()
method to prompt the user for input:
n = input("Type something: ")
Type the outer if
statement, which uses the isalnum()
function.
if n.isalnum():
Type the two nested if
statements, which use the isalpha()
method and the isnumeric()
method, respectively, and assign appropriate text to the variable r
.
if n.isalpha():
r = "alphabetical"
if n.isnumeric():
r = "numeric"
Type the first elif
statement, which uses the isspace()
method.
elif n.isspace():
r = "space-based"
Type the second elif
statement, which uses the isascii()
method.
elif n.isascii():
r = "ASCII text"
Type the else
statement and its text:
else:
r = "a mystery"
Type the following print()
statement to display the information about n
:
print(n + " is " + r + ".")
Click Run Python File in Terminal ().
The Terminal pane appears.
Type your choice of input, and then press .
Python displays the appropriate message.
3.12.161.165