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 tostart
to get the consecutive numbers.
Example:
>>> # comenzando en 2, parar en 20, saltando de 3 en 3 >>> for i in range(2, 20, 3): ... print(i) ... 2 5 8 11 14 17 >>> # comenzando en 100, parar en 0, saltando de -10 en -10 >>> for i in range(100, 0, -10): ... print(i) ... 100 90 80 70 60 50 40 30 20 10
With two arguments:
- only the
start
andstop
parameters are used. step
parameter is assumed equal to one
Example:
>>> for i in range(5, 11): ... print(i) ... 5 6 7 8 9 10 >>> for i in range(-6, 3): ... print(i) ... -6 -5 -4 -3 -2 -1 0 1 2
With an argument:
- The argument is copied into the
stop
parameter. start
parameter is assumed to be zero.step
parameter is assumed equal to one
Example:
>>> for i in range(6): ... print(i) ... 0 1 2 3 4 5 >>> for i in range(3): ... print(i) ... 0 1 2
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¶
Write a program that prints all even numbers between 2 and 20, inclusive.
Write a program that prints all the odd numbers between 1 and 19, inclusive.
Write a program that prints a countdown that starts by printing 10 and ends by printing 0.
Write a program that writes the following list:
50 45 40 35 30 25 20
Write a program that writes the following list:
-50 -45 -40 -35 -30 -25 -20
Write a program that adds up all the first 'n' odd numbers and checks that the result is equal to the square of 'n'.
Hint:
num = input('Introduce cuántos impares sumaremos: ') num = int(num) suma = 0 for ... in range(1, num*2, ... ): suma = ... print('La suma de los', num, 'primeros impares es igual a', suma) print('El cuadrado de', num, 'es igual a', num*num)