Python range Function with Examples


How to Use the Python range() Function

In this tutorial, you'll learn what the range function does in Python and how to use it. In Python, range() is a built-in function that returns a sequence of numbers, which starts from a given number up to the specified number. We generally use the range function with the FOR loop statement to loop through a block of code.

Python range() Function Syntax

The syntax of the range() function is as follows:

range(stop)

or:

range(start, stop [, step])

Remarks

  • The start argument is a starting integer number of the sequence. It defaults to 0, if not specified.
  • The stop argument is an integer number that range function generates up to, but not including this number.
  • The step argument is a difference between each number in the sequence. It defaults to 1, if not specified.

For the first syntax, range() returns a sequence of numbers up to, but not including the stop number. For example, range(10) returns a sequence of numbers, starting from 0 to 9.

And, for the second syntax, the step argument is optional, and it defaults to 1, if not specified.

Examples

Now, let's take a look at an example:

range(2,10)

Here, the step argument omitted and defaults to 1. The range(2,10) generates a sequence of numbers as follows:

= 2, 2 + 1, 2 + 2, 2 + 3, 2 + 4, 2 + 5, 2 + 6, 2 + 7

=2, 3, 4, 5, 6, 7, 8, 9

Next, let's take a look at another example below:

range(2,10,2)

Here, the step argument is 2, so the range() function generates a sequence of numbers as follows:

=2, 2 + 2, 2 + 4, 2 + 6

=2, 4, 6, 8

Using range() with the FOR Loop Statement

In this section, I show you how we use the range() function with a FOR loop statement.

Example 1

The following sample program illustrates an example of how to use the range() function with the FOR loop statement to loop through a block of code:

sum = 0;
for i in range(10):
sum += i
print("The total is ", sum)

The above program calculates the sum of all numbers in the sequence generated by the range(10). The output of the above program is as follows:

= 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9

= 45

Example 2

The following program illustrates another example of how to use the range() function with the FOR loop statement:

for i in range(2, 10, 3):
print("The value of i is ", i)

Here, as you can see, all three arguments used.

The result is as follows:

The value of i is 2
The value of i is 5
The value of i is 8

In this tutorial, you've learned what the Python range() function does and how to use it. The range() is a built-in function that generates a sequence of numbers. We generally use it with the FOR loop statement to loop through a block of code.

Leave a Reply

Your email address will not be published. Required fields are marked *