Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

The range() Function

In Python, the range() function is a powerful tool for generating a sequence of numbers. It is commonly used with loops to iterate over a range of values efficiently.

Understanding range()

The range() function produces a sequence of numbers, starting from a specified value (default is 0) and ending before a specified stop value. It follows this syntax:

range(start, stop, step)
  • start (optional): The beginning number (default is 0).
  • stop (required): The number where the sequence stops (not included).
  • step (optional): The increment between each number (default is 1).

Examples

Basic Usage

for i in range(5):  # Generates numbers from 0 to 4
    print(i)

Output:

0
1
2
3
4

Using start and stop

for i in range(2, 7):  # Generates numbers from 2 to 6
    print(i)

Output:

2
3
4
5
6

Using step

for i in range(1, 10, 2):  # Generates numbers from 1 to 9 with a step of 2
    print(i)

Output:

1
3
5
7
9

Counting Backwards

for i in range(10, 0, -2):  # Counts down from 10 to 2, decreasing by 2 each time
    print(i)

Output:

10
8
6
4
2

Converting range() to a List

If you want to see the values of range() at once, you can convert it to a list:

print(list(range(5)))

Output:

[0, 1, 2, 3, 4]

Exercise: Try It Yourself!

  1. Create a loop that prints the numbers from 5 to 15 using range().
  2. Write a loop using range() that prints all even numbers between 2 and 20.
  3. Generate a countdown from 10 to 1 using range().