TutorialAce

Python | Java | MySQL | Excel

Python Tutorial

Python range Function with Examples

How to Use the Python range Function

In this tutorial, we'll learn what does range function do in Python and how to use it. The Python range is built-in function that returns a sequence of numbers, starting from a given number up to the specified number. This function is generally used to iterate over with a For loop.

Python range Function Syntax

The syntax of the range function is as follows:

range(stop)

or:

range(start, stop [, step])

  • The start argument is a starting integer number of the sequence. It defaults to 0, if not specified.
  • The stop argument is a 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.

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 the following example:

range(2,10)

Here, the step argument is 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 the range() with a For Loop

In this section, I give you examples how to use the range() function with a For loop.

Example 1

The following code illustrates how to use the range() function with a For loop:

sum = 0;

for i in range(10):

sum += i

print("The total is ", sum)

This program calculates the sum of all numbers in the sequence generated by the range(10). The program sums a sequence of numbers as follows:

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

= 45

Example 2

The following illustrates how to use the range() function with a For loop:

for i in range(2, 10, 3):

print("The value of i is ", i)

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, we've learned what does the Python range() function do and how to use it. The range() is a built-in function that generates a sequence of numbers and it's generally used to iterate over with a For loop.

Leave a Reply