In this article, you’ll learn how to explain the range function in Python. Before we get started, if you want to conditional statements in python, please go through the following article: Define Functions in Python.
One of Python’s built-in immutable sequence types is range(). This function is extensively used in loops to control the number of types of loop that have to run. In simple words range is used to generate a sequence between the given values.
The range() function can take 1 to 3 of the following arguments:
- Start: The integer value for the origin of the sequence, if not passed implicitly it’s 0
- Stop: The integer value up to which the sequence will get generated but won’t include this number. This is a required argument which must be passed,
- Step: Establishes the difference between each iteration it can be positive or negative if not given the default step is 1
The order of arguments is as follows, range(start, stop, step). Note that all parameters must be integers however they can be positive or negative.
Using range Function In Python
Let’s start with generating a simple series and printing it out
1 2 3 4 |
for i in range(0, 6, 1):
print(i) |
1 2 3 4 5 6 7 8 | 0 1 2 3 4 5 |
1 2 3 4 |
for i in range(6):
print(i) |
1 2 3 4 5 6 7 8 | 0 1 2 3 4 5 |
1 2 3 4 |
for i in range(30,0,-5):
print(i) |
1 2 3 4 5 6 7 8 | 30 25 20 15 10 5 |
1 2 3 4 5 |
li = ["1", "text", "2", "more Text",3,4,5]
for i in range(len(li)):
print(li[i]) |
1 2 3 4 5 6 7 8 9 | 1 text 2
more Text 3 4 5 |
1 2 3 4 5 6 |
>>> x = list(range(6))
>>> x
[0, 1, 2, 3, 4, 5] |
Leave a Comment