Control Flow Statements
A program’s
control
flow is the order
in which the program’s code executes. The control
flow of a Python program is regulated by conditional statements,
loops, and function calls. This section covers the
if statement and for and
while loops; functions are covered later in this
chapter. Raising and handling exceptions also affects control flow;
exceptions are covered in Chapter 6.
The if Statement
Often, you need to execute some
statements only if some condition holds, or choose statements to
execute depending on several mutually exclusive conditions. The
Python compound statement if, which uses
if, elif, and
else clauses, lets you conditionally execute
blocks of statements. Here’s the syntax for the
if statement:
ifexpression:statement(s)elifexpression:statement(s)elifexpression:statement(s)... else:statement(s)
The
elif and else clauses are
optional. Note that unlike some languages, Python does not have a
switch statement, so you must use
if, elif, and
else for all conditional processing.
Here’s a typical if statement:
if x < 0: print "x is negative" elif x % 2: print "x is positive and odd" else: print "x is even and non-negative"
When there are multiple statements in a clause (i.e., the clause controls a block of statements), the statements are placed on separate logical lines after the line containing the clause’s keyword (known as the header line of the clause) and indented rightward from the header line. The block terminates when the indentation ...
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