Control Structures
The
for
loop actually operates over lists, not
numbers:
>>> for item in mylunch: ... print item ... spam eggs tea raspberries wafer-thin mint >>>
There are several things to note at this point. First, after typing
the
colon and
pressing the Return key, Python indents the next line, and you
don’t have to type anything to end the for
loop. Python actually uses
indentation for
syntax, saving typing and making the language highly readable: the
layout of code on the page indicates its structure. A second point is
that the
>>>
prompt changes to
... for subsequent lines. This
indicates that Python knows you are entering a multiline statement at
the command prompt.
Another common structure is the
while
loop:
>>> x = 2 >>> while x < 50: ... x = x * 2 ... print x ... 4 8 16 32 64 >>>
The if
structure is also present; the
else
clause is optional:
>>> if 'chocolate' in mylunch: ... print "that's not allowed" ... else: ... print "enjoy your meal" ... enjoy your meal >>>
You can also have a number of intermediate
elif
clauses, short for else-if. These allow
something like the
switch
or case
statements in other languages:
>>> salary = 20000 >>> if salary < 4000: ... tax_rate = 0 ... elif salary < 29000: ... tax_rate = 0.25 ... elif salary < 100000: ... tax_rate = 0.4 ... else: ... emigrate() # that's a function call ... >>>
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