7.2 Conditional statements
Conditional Statements
In many situations, actions and results depends on a specific set of conditions being satisfied. For example, individuals in randomized controlled trials receive the treatment if they have been assigned to the treatment group. A gambler makes money if she wins her bet.
In this section we will learn how to describe such situations using code. A conditional statement is a multi-line statement that allows Python to choose among different alternatives based on the truth value of an expression. While conditional statements can appear anywhere, they appear most often within the body of a function in order to express alternative behavior depending on argument values.
A conditional statement always begins with an if
header, which is a single line followed by an indented body. The body is only executed if the expression directly following if
(called the if expression) evaluates to a true value. If the if expression evaluates to a false value, then the body of the if
is skipped.
Let us start defining a function that returns the string 'Positive'
for a positive number:
def classify(x):
if x > 0:
return 'Positive'
Let us work through what Python will do when we evaluate classify(3)
.
- Evaluate
classify
to the internal representation (IR) of the function; - Evaluate
3
to give the IR of the integer 3 -
Call the IR of the function, with the IR of int 3. So:
- Python enters function world
- The new variable
x
gets the value IR of int 3. - Python executes the function body
All this is revision from functions.
What happens in the function body, with x = 3
?
- Python evaluates the if expression
x > 0
. The result is the IR ofTrue
. This is a true value, so Python executes the body of the if statement. - The body of the if statement is the single line
return 'Positive'
.'Positive'
evaluates to the IR of the string'Positive'
.return
exits function world, returning this value.
classify(3)
'Positive'
The classify
function returns 'Positive'
if the input is a
positive number, like 3
. But if the input is not a positive number,
such as -3
, then this happens, in the function body:
x
has the value IR of int -3.x > 0
evaluates toFalse
, so Python skips the body of the if statement.- The function body ends without executing a
return
statement.
So, the function body finishes without a return
, and the function
returns None. This is invisible to us, so it looks like the
function returns nothing at all:
classify(-3)
We can catch the result, and check it is None
(see the None
page.
r = classify(-3)
r is None
True
Let us refine our function to return Not positive
if the input is a
negative number. We can do this by adding an else
clause. If the if
expression evaluates to a true value, then Python executes the first
clause, after the if expression, as before. If it evaluates to a false value, Python executes the clause following the else
, instead.
def classify(x):
if x > 0:
return 'Positive'
else:
return 'Not positive'
Imagine we evaluate classify(-3)
again. Python enters function world, and sets x
to have the value IR of int -3. It checks x > 0
and finds a false value, so it skips the first clause, and executes the clause following else:
. This return
s 'Not positive'
.
Now imagine we prefer our function to return 'Negative
for negative values and Zero
if the input value is 0. It seems like we need three clauses, one each for positive, negative and 0 values.
We can do this by adding an elif
clause, where elif
is Python’s
shorthand for the phrase “else if”.
def classify(x):
if x > 0:
return 'Positive'
elif x == 0:
return 'Zero'
else:
return 'Negative'
Now classify
returns the correct answer when the input is -3, 0, or 3:
classify(3)
'Positive'
classify(0)
'Zero'
classify(-3)
'Negative'
If the input is 3, Python enters function world, sets x
to have the value 3, and evaluates the if expression x < 0
. The expression is a true value, so Python executes the first clause and return
s 'Positive'
.
If the input is 0, Python enters function world, sets x
to have the value 0, and evaluates the if expression x < 0
. The expression is a false value, so Python moves on to the next clause, which is elif x == 0:
. This has another if expression x == 0
. It is a true value, so Python executes this clause, and return
s 'Zero
.
If the input is -3, Python enters function world, sets x
to have the value -3, and evaluates the if expression x < 0
. The expression is a false value, so Python moves on to the next clause, which is elif x == 0
. This expression is also a false, value so Python moves to the next clause, which is the else:
clause, and executes that, return
ing 'Negative'
.
We can have as many elif
clauses as we want. For example, imagine we
want to classify the number into one of the following categories:
- above 10 (
'Large positive'
) - from (not including) 0 through 10 (
'Small positive'
) - exactly 0 (
'Zero'
) - from (not including) 0 through -10 (
'Small negative'
) - below -10 (
'Large negative'
)
def classify(x):
if x > 10:
return 'Large positive'
elif x > 0:
return 'Small positive'
elif x == 0:
return 'Zero'
elif x >= -10: # Greater than or equal to
return 'Small negative'
else:
return 'Large negative'
classify(-100)
'Large negative'
classify(0)
'Zero'
The General Form
A conditional statement can also have multiple clauses with multiple bodies, and only one of those bodies can ever be executed. The general format of a multi-clause conditional statement appears below.
if <if expression>:
<if body>
elif <elif expression 0>:
<elif body 0>
elif <elif expression 1>:
<elif body 1>
...
else:
<else body>
There is always exactly one if
clause, but there can be any number of
elif
clauses. Python will evaluate the if
and elif
expressions in
the headers in order until one is found that is a true value, then
execute the corresponding body. The else
clause is optional. When an
else
header is provided, its else body is executed only if none of
the header expressions of the previous clauses are true. The else
clause must always come at the end (or not at all).
Now try the exercises.