14. The range() function

range(start, stop, step)

The range() function is used to create a range of numbers in a for loop. It has three parameters with default values, so it can have one, two, or three arguments.

With three arguments:

  • start is the first integer that the range starts with.
  • stop is the number that stops the range. It never reaches that value.
  • step is the value that is added to start to get the consecutive numbers.

Example:

>>> # comenzando en 2, parar en 20, saltando de 3 en 3
>>> list( range(2, 20, 3) )
    [2, 5, 8, 11, 14, 17]

>>> # comenzando en 100, parar en 0, saltando de -10 en -10
>>> list( range(100, 0, -10) )
    [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

With two arguments:

only the start and stop parameters are used. step is assumed to be equal to one.

Example:

>>> list( range(5, 11) )
    [5, 6, 7, 8, 9, 10]

>>> list( range(-10, 1) )
    [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0]

With an argument:

  • The argument is copied into the stop parameter.
  • start is assumed to be zero.
  • step is assumed equal to one

Example:

>>> list( range(10) )
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list( range(2) )
    [0, 1]

Since the range starts at zero, the number of elements in the range is equal to the number we write inside the range function.

Exercises

  1. Write a program that prints all even numbers between 2 and 20, inclusive.

  2. Write a program that prints all the odd numbers between 1 and 19, inclusive.

  3. Write a program that prints a countdown that starts by printing 10 and ends by printing 0.

  4. Write a program that writes the following list:

    50
    45
    40
    35
    30
    25
    20
    
  5. Write a program that writes the following list:

    -50
    -45
    -40
    -35
    -30
    -25
    -20