Control Flow - Page 1
September 14, 2001
This chapter describes statements related to the control flow of
a program. Topics include conditionals, loops, and exceptions.
Conditionals
The if, else, and elif
statements control conditional code execution. The general format
of a conditional statement is as follows:
if expression:
statements
elif expression:
statements
elif expression:
statements
. . .
else:
statements
If no action is to be taken, you can omit both the
else and elif clauses of a conditional.
Use the pass statement if no statements exist for a particular
clause:
if expression:
pass # Do nothing
else:
statements
Loops
You implement loops using the for and
while statements. For example:
while expression :
statements
for i in s:
statements
The while statement executes statements until the associated
expression evaluates to false. The for statement iterates over
all the elements in a sequence until no more elements are
available. If the elements of the sequence are tuples of
identical size, you can use the following variation of the
for statement:
for x , y , z in s :
statements 1
In this case, s must be a sequence of tuples, each
with three elements. On each iteration, the contents of the
variables x, y, and z are
assigned the contents of the corresponding tuple.
To break out of a loop, use the break statement. For
example, the following function reads lines of text from the user
until an empty line of text is entered:
while 1:
cmd = raw_ input('Enter command > ')
if not cmd:
break # No input, stop loop
# process the command
. . .
To jump to the next iteration of a loop (skipping the remainder
of the loop body), use the continue statement. This
statement tends to be used less often, but is sometimes useful
when the process of reversing a test and indenting another level
would make the program too deeply nested or unnecessarily
complicated. As an example, the following loop prints only the
non-negative elements of a list:
for a in s:
if a < 0:
continue # Skip negative elements
print a
The break and continue statements apply
only to the innermost loop being executed. If it's necessary to
break out of a deeply nested loop structure, you can use an
exception. Python doesn't provide a goto statement.
You can also attach the else statement to loop
constructs, as in the following example:
# while-else
while i < 10:
do something
i = i + 1
else:
print Done
# for-else
for a in s:
if a = = Foo :
break
else:
print Not found!
The else clause of a loop executes only if the loop runs to
completion. This either occurs immediately (if the loop wouldn't
execute at all) or after the last iteration. On the other hand,
if the loop is terminated early using the break
statement, the else clause is skipped.
Python Essential Reference, Second Edition
Exceptions - Page 2
|