range( first, last, step )

produce a range of numbers

Use: range(  first, last, inc )
Description: Used in the for command to produce a sequence (range) of numbers.
Parameters: first Optional, sets the first number in the sequence, If this parameter is not present, the first number is 0
last Required, sets the last number in the sequence. (note that the loop will stop one before this number)
inc Optional, only used if 3 parameters are present. It specifies the increment value, it can be positive or negative, but it should not be set to 0.
Returns: None
Related: for, break, continue


The range command is used with the for command to run a block of code multiple times.

Each time the for command runs through its loop, the range command is used to give the loop variable a new number. The parameters for the range command are used to set the number of times the loop runs, the first , last and increment value of the loop variable.

In the simplest form the range command uses 1 parameter e.g. range( num ). Used in a for loop this will repeat the loop num times.

Example:

for a in range(10):                      # do 10 times
   print 'the value of a is', a

Produces

the value of a is    0
the value of a is    1
the value of a is    2
the value of a is    3
the value of a is    4
the value of a is    5
the value of a is    6
the value of a is    7
the value of a is    8
the value of a is    9

Note: that in this example the loop runs 10 times, the loop variable a starts with value 0 and increments by each time, but it ends with the loop variable a equal to 9  (the loop variable a never gets to 10).  This catches a lot of people out.

When the range command is used with 2 parameters, it defines the first and last values of the loop variable.

for b in range(6,10):
     print 'the value of b is', b

Produces

the value of b is 6
the value of b is 7
the value of b is 8
the value of b is 9

This runs the loop 4 times, with b starting at 6 and finishing at 9.

When the range command is used with 3 parameters the first, last and the increment are defined.

for c in range(6,10,2):
     print 'the value of c is', c

Produces

the value of c is   6
the value of c is   8

Using a negative increment value the loop variable will decrease each time round the loop.

for d in range(4,0,-1):
     print 'the value of d is', d

Produces

the value of d is   4
the value of d is   3
the value of d is   2
the value of d is   1

In this loop it only goes 4 times round the loop and the loop variable d never gets to 0