How to Use the Python range() Function
In this tutorial, you will learn what Python's range function does and how to use it. In Python, range() is a built-in function that starts with a given number and returns a sequence of numbers up to a given number. Typically, the range function is used in conjunction with a 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 an integer value that is the starting point of the sequence. If not specified, it defaults to 0.
- The stop argument is the integer value produced by the range function, up to and including this number.
- The step argument is the difference between each number in the sequence. If not specified, it defaults to 1.
In the first syntax, range() returns the sequence of numbers up to and including the stop number. For example, range(10) returns the sequence of numbers from 0 to 9.
In the second syntax, the step argument is optional and defaults to 1 if not specified.
Examples
Now let's look at an example:
range(2,10)
The step argument is omitted, and defaults to 1. range(2,10) produces the following sequence of numbers:
= 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 look at another example:
range(2,10,2)
Here, since the step argument of is 2, the range() function produces a sequence of numbers like this:
=2, 2 + 2, 2 + 4, 2 + 6
=2, 4, 6, 8
Using range() in a FOR loop statement
This section shows how to use the range() function in a FOR loop statement.
Example 1
The following sample program shows an example of looping through a code block using the Range() function and a FOR loop statement:
sum = 0; for i in range(10): sum += i print("The total is ", sum)
The above program computes the sum of all the numbers in the sequence produced by 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 shows another example of using the range() function in a FOR loop statement:
for i in range(2, 10, 3): print("The value of i is ", i)
As you can see, all three arguments are used here.
The output is as follows:
The value of i is 2
The value of i is 5
The value of i is 8
Summary
In this tutorial, you learned what Python's range() function does and how to use it. Range() is a built-in function that generates a sequence of numbers. It is typically used in conjunction with a FOR loop statement to loop through a code block.