Chapter 12. if Tests and Syntax Rules
This chapter presents the Python if
statement, which is the main statement used for selecting from alternative
actions based on test results. Because this is our first in-depth look
at compound statements—statements that
embed other statements—we will also explore the general concepts behind the
Python statement syntax model here in more detail than we did in the
introduction in Chapter 10. Because
the if statement introduces the notion of
tests, this chapter will also deal with Boolean expressions, cover the
“ternary” if expression, and fill in some
details on truth tests in general.
if Statements
In simple terms, the Python if statement
selects actions to perform. Along with its expression counterpart, it’s
the primary selection tool in Python and represents much of the
logic a Python program possesses. It’s also our first
compound statement. Like all compound Python statements, the if statement may contain other statements,
including other ifs. In fact, Python
lets you combine statements in a program sequentially (so that they
execute one after another), and in an arbitrarily nested fashion (so that
they execute only under certain conditions such as selections and
loops).
General Format
The Python if statement is
typical of if
statements in most procedural languages. It takes the form of an
if test, followed by one or more
optional elif (“else if”) tests and a
final optional else block. The tests
and the else part each have an associated block ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access