3.3. Range

syntaks: range(begynd, slut - 1, step) - slut er nødvendig.
>>> range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9.10]
>>> range(0,21,2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>> range(0,40,3)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39]
>>> range(1,-11,-1)
[1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
>>> range(40,0,-5)
[40, 35, 30, 25, 20, 15, 10, 5]
>>> for i in range(1,11):
...     print i,
...
1 2 3 4 5 6 7 8 9 10
Range fungerer også ved nedtælling:
>>> for i in range(10,0, -1):
...     print i,
...
10 9 8 7 6 5 4 3 2 1
>>> for i in range(100,0, -5):
...     print i,
...
100 95 90 85 80 75 70 65 60 55 50 45 40 35 30 25 20 15 10 5
>>>
2 metoder til udskrift af kvadrat- og kubiktal:
>>> import string
>>> for x in range(1, 11):
...     print string.rjust(repr(x), 2), string.rjust(repr(x*x), 3),
...     print string.rjust(repr(x*x*x), 4)
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
>>> for x in range(1,11):
...     print '%2d %3d %4d' % (x, x*x, x*x*x)
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000