O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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
...     
>>>

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required