Conditionals
Boolean Expressions
A Boolean expression is an expression that is either true or false. The following examples use the operator ==
, which compares two operands and produces True
if they are equal and False
otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
True
and False
are special values that belong to the type bool
; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
The ==
operator is a relational operator; the others are:
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
Warning!
Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign (=
) instead of a double equal sign (==
). Remember that =
is an assignment operator and ==
is a relational operator. There is no such thing as =<
or =>
.
Logical Operators
There are three logical operators: and
, or
, and not
. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10
is true only if x
is greater than 0 and less than 10.
(n % 2 == 0) or (n % 3 == 0)
is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3.
Finally, the not
operator negates a Boolean expression, so not (x > y)
is true if x > y
is false, that is, if x
is less than or equal to y
.
Warning! The operands of the logical operators should be Boolean expressions, but Python is not very strict. In fact, any nonzero number is interpreted as True
:
>>> 42 and True
True
This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).
Conditional Execution
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if
statement:
if x > 0:
print('x is positive')
The Boolean expression after if
is called the condition. If it is true, the indented statement runs. If not, nothing happens.
if
statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements.
There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass
statement, which does nothing.
if x < 0:
pass # TODO: need to handle negative values!
Alternative Execution
A second form of the if
statement is “alternative execution”, in which there are two possibilities and the condition determines which one runs. The syntax looks like this:
if x % 2 == 0:
print('x is even')
else:
print('x is odd')
If the remainder when x
is divided by 2 is 0, then we know that x
is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution.
Chained Conditionals
Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
elif
is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of elif
statements. If there is an else
clause, it has to be at the end, but there doesn’t have to be one.
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.
Nested Conditionals
One conditional can also be nested within another. We could have written the example in the previous section like this:
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if
statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:
if 0 < x:
if x < 10:
print('x is a positive single-digit number.')
The print
statement runs only if we make it past both conditionals, so we can get the same effect with the and
operator:
if 0 < x and x < 10:
print('x is a positive single-digit number.')
For this kind of condition, Python provides a more concise option:
if 0 < x < 10:
print('x is a positive single-digit number.')
Debugging
When a syntax or runtime error occurs, the error message contains a lot of information, but it can be overwhelming. The most useful parts are usually:
- What kind of error it was, and
- Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them.
>>> x = 5
>>> y = 6
File "<stdin>", line 1
y = 6
^
IndentationError: unexpected indent
In this example, the problem is that the second line is indented by one space. But the error message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line.
The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio in decibels. The formula is:
\[SNR_\text{db} = 10 \log_{10}(P_\text{signal} / P_\text{noise})\]In Python, you might write something like this:
import math
signal_power = 9
noise_power = 10
ratio = signal_power // noise_power
decibels = 10 * math.log10(ratio)
print(decibels)
When you run this program, you get an exception:
Traceback (most recent call last):
File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio)
ValueError: math domain error
The error message indicates line 5, but there is nothing wrong with that line. To find the real error, it might be useful to print the value of ratio
, which turns out to be 0. The problem is in line 4, which uses floor division instead of floating-point division.
You should take the time to read error messages carefully, but don’t assume that everything they say is correct.
Glossary
- Boolean expression
- An expression whose value is either
True
orFalse
. - relational operator
- One of the operators that compares its operands:
==
,!=
,>
,<
,>=
, and<=
. - logical operator
- One of the operators that combines Boolean expressions:
and
,or
, andnot
. - conditional statement
- A statement that controls the flow of execution depending on some condition.
- condition
- The Boolean expression in a conditional statement that determines which branch runs.
- compound statement
- A statement that consists of a header and a body. The header ends with a colon (
:
). The body is indented relative to the header. - branch
- One of the alternative sequences of statements in a conditional statement.
- chained conditional
- A conditional statement with a series of alternative branches.
- nested conditional
- A conditional statement that appears in one of the branches of another conditional statement.
Self Check
Look through the following piece of code and then answer the following questions.
val = int(input("Enter an integer: "))
if val == 5:
print("red")
elif val < 5:
if val >= 0:
print("green")
else:
print("blue")
else:
if val > 10:
print("purple")
a. Under what values of val
will red be printed?
b. Under what values of val
will green be printed?
c. Under what values of val
will blue be printed?
d. Under what values of val
will purple be printed?
e. Under what values of val
will nothing be printed?
f. Examine the following conditional and determine if it is equivalent to the conditional structure above.
if val < 0:
print("blue")
elif val < 5:
print("green")
elif val == 5:
print("red")
elif val > 10:
print("purple")
g. Do you think the first or the second conditional is easier to read? Why?
Acknowledgment:
This reading was originally written by Allen Downey in his open source book Think Python 2e. Downey's book is licensed under the GNU Free Documentation License, which allows users to copy, modify, and distribute the book.
This reading was modified by Titus H. Klinge in 2021 and presented above under the same license in order to better serve the students of this course.