Main.ForLoops History

Hide minor edits - Show changes to markup

February 04, 2010, at 08:46 PM MST by 71.196.160.210 -
Added lines 1-50:

(:source lang=python:)

"""Examples of iteration using for loops"""

  1. for loops are an alternative to the while loop
  2. first let's look at the range function

print range(1, 10)

  1. this generates the numbers 1 thru 9
  2. if the first number you want to generate is 0 you can use
  3. an abbreviated version:

print range(10)

  1. if you want to generate numbers that have a fixed step
  2. between them you can use

print range(1, 20, 2)

  1. the last argument is the step
  2. 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
  1. a note on ranges:
  2. a range generates a list of numbers

a = range(10)

  1. is the same as:

a = [0,1,2,3,4,5,6,7,8,9]

  1. therefore

for i in range(10) : print i,

  1. is the same as:

for i in [0,1,2,3,4,5,6,7,8,9] : print i,

  1. the step in a range can be negative:

print range(10, 0, -1)

(:sourceend:)