Control
Table of Contents
1. Statements
A statement is executed by the interpreter to perform an action.
We can also define compound statements, which are statements that span multiple lines. Generally, there is some header, followed by an indented block of statements known as the suite. The header with its suite is known as a clause. Compound statements can have multiple clauses.
In a compound statement, the first header determines the statement's type. For each clause, the header of that clause controls the suite that follows. An example of a compound statement are def statements.
2. Conditional Statements
A conditional statement is a compound statement that controls execution flow. The following example is a conditional statement that uses if, elif, and else:
def absolute_value(x):
"""Return the absolute value of x."""
if x < 0:
return -x
elif x == 0:
return 0
else:
return x
This conditional statement consists of one statement, three clauses, three headers, and three suites. A conditional statement:
- Always starts with an
ifclause. - Followed by zero or more
elifclauses. - Ends with zero or one
elseclause.
2.1. Procedure for Conditional Statements
Each clause is considered in order. For each clause:
- Evaluate the header's expression.
- If it is a
Truevalue, execute the suite and skip the remaining clauses.
Notice that a conditional statement only ever executes one clause.
2.2. Boolean Contexts
A boolean context is a context in which we only care if the expression evaluates to True or False. Examples of False values include False, 0, '', None, and others. Anything other than a False value is a True value. Examples of boolean contexts include the headers for conditional statements and while.