More about the range() function

Python's built-in function range() is often used to generate integers, like in the range(10) we used before.

range(10) is the simplest form of range() function. It's full form is range(start, end, step). If you only provide one parameter, then it's used as end, with 0 as the default value for start and 1 as the default value for step. So range(10) is the same as range(0, 10, 1). The generated sequence begins at 0 instead of 1 and does not include the end number.

Let's use examples to show how range() function works:

  • range(5) generates integers: 0, 1, 2, 3, 4, while 5 is not included.
  • range(2, 10) generates 2 through 9.
  • range (2, 10, 2) generates: 2, 4, 6, 8.
  • range(10, 5, -1) generates: 10, 9, 8, 7, 6 (notice the negative step).

Example range() function in for loops

It's easy to generate integers in a patterned sequence:

for i in range (3, 8):
    print (i)       # 3,4,5,6,7 (not including 8)

for i in range (1, 10, 2):
    print (i)       # 1,3,5,7,9

for k in range(10, 1, -2):
    print(k)        # 10,8,6,4,2

results matching ""

    No results matching ""