range() Function

range() Function

In Python, the range() function is a versatile tool that plays a crucial role in control flow, especially in iterable loops. It is a built-in function that generates a sequence of numbers, which can be used to iterate over with for loop, or other forms of loops and iterations.

The Basic Syntax of Range Function

The range() function is commonly used in the following three forms:

  • range(stop): This generates a sequence starting from 0 to stop - 1.
  • range(start, stop): This generates a sequence starting from start to stop - 1.
  • range(start, stop, step): This generates a sequence starting from start to stop - 1, with a step of the specified value.

Here is how the syntax generally looks:

1range([start], stop[, step])

Examples of Range Function

Let’s get a better understanding of how range() function works with a few different examples.

Example 1: Range with One Argument

When range() function is called with only one argument (the stop value), it generates a sequence of integers ranging from 0 to stop - 1.

1for i in range(5):
2    print(i, end=' ')

Running this code would output: 0 1 2 3 4

Example 2: Range with Two Arguments

When range() function is called with two arguments (the start and stop values), it generates a sequence of integers ranging from start to stop - 1.

1for i in range(2, 7):
2    print(i, end=' ')

Running this code would output: 2 3 4 5 6

Example 3: Range with Three Arguments

When range() function is called with three arguments (the start, stop, and step values), it generates a sequence of integers from start, incrementing by step, until a number lower than stop is reached.

1for i in range(1, 10, 2):
2    print(i, end=' ')

Running this code would output: 1 3 5 7 9

Note

The step value can also be negative which makes the range function to generate a decreasing sequence.

Use of Range Function in Script Control Flow

In Python programs, the range() function is mostly used with iterable loops such as for loops to control the flow of the program. Here’s a simple example using the range function to print the square of numbers from 1 to n.

1n = 5
2for i in range(1, n+1):
3    print("The square of ", i, " is ", i*i)

This program would output:

The square of  1  is  1
The square of  2  is  4
The square of  3  is  9
The square of  4  is  16
The square of  5  is  25