Loops in python.
Goal: Learn about loops
in
python.
We saw the simple loop using the while statement in the previous examples. Other looping constructs such as the for statement are available to the user. It is important to note that statements within the loop are indented. An example of its usage is:
for i in range(3):
print "10 raised to ", i, " is ", 10**i
Will produce the result:
10 raised to 0 is 1Note that a=range(3) is equivalent to a=[0,1,2]. Similarly the range(1, 6) is equivalent to [1,2,3,4,5] and range(10, 8, -1) is equivalent to [10, 9]. To generalize, range(i, j, k) produces a list of integers from i to j-1 using a stride k. If i is omitted, it is taken to be zero and k defaults to 1 if omitted. A more efficient (in terms of memory and runtime) is the xrange() function used exactly like range().
10 raised to 1 is 10
10 raised to 2 is 100
One can also loop through lists using the for statement so:
mylist = ['a', 'b', 3]Produces the output:
for item in mylist:
print item
a
b
3