"""Examples of iteration using for loops"""
# for loops are an alternative to the while loop
# first let's look at the range function
print range(1, 10)
# this generates the numbers 1 thru 9
# if the first number you want to generate is 0 you can use
# an abbreviated version:
print range(10)
# if you want to generate numbers that have a fixed step
# between them you can use
print range(1, 20, 2)
# the last argument is the step
# next we see how to iterate over a range using the for loop:
def sum(n) :
s = 0
for i in range(1, n + 1) :
s += i
return s
def sum_odd(n) :
s = 0
for i in range(1, n + 1, 2) :
s += i
return s
# a note on ranges:
# a range generates a list of numbers
a = range(10)
# is the same as:
a = [0,1,2,3,4,5,6,7,8,9]
# therefore
for i in range(10) : print i,
# is the same as:
for i in [0,1,2,3,4,5,6,7,8,9] : print i,
# the step in a range can be negative:
print range(10, 0, -1)
