Basic Python Statements, cont. |
<Part 2< |
for Loops
The for loop is a sequence iterator for Python. It will work on nearly anything: strings, lists, tuples, etc. I've talked about for loops before so I won't get into much more detail about them. The main format is below:
for <target> in <object>: # assign object items to target
<statements>
if <test>: break # exit loop now, skip else
if <test>: continue # go to top of loop now
else:
<statements> # if we didn't hit a 'break'
From Learning Python:
When Python runs a for loop, it assigns items in the sequence object to the target, one by one, and executes the loop body for each. * The loop body typically uses the assignment target to refer to the current item in the sequence, as though it were a cursor stepping through the sequence. Technically, the for works by repeatedly indexing the sequence object on successively higher indexes (starting at zero), until an index out-of-bounds exception is raised.
Because for loops automatically manage sequence indexing behind the scenes, they replace most of the counter style loops you may be used to coding in languages like C.
Related to for loops are range and counter loops. The range function auto-builds a list of integers for you. Typically it's used to create indexes for a for statement but you can use it anywhere.
>>> range(5), range(2, 5), range(0, 10, 2)
([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])
As you can see, a single argument gives you a list of integers, starting from 0 and ending at one less than the argument. Two arguments gives a starting number and the max value while three arguments adds a stepping value, i.e. how many numbers to skip between each value.
Well, that's it for this installment. As you can see, Python is a pretty simple language that "automates" many of the features you'd have to code by hand in other languages. Next time I'll discuss using procedural-style functions in Python followed by a more in-depth look at modules.