Python range() function
Hello in this tutorial, we will understand the range() method in python programming.
1. Introduction to range()
Python range()
method is useful to generate an immutable sequence of numbers based on the given number. It is represented by the following syntax –
Syntax
range(start, stop[, step_size])
The method consists of 3 parameters –
start
: It defines the lower limit and defaults to zero. It is an optional argumentstop
: It defines the upper limit that generates the numbers up to the specified. It is a mandatory argument and never includes the stop number in its resultstep_size
: It defines the increment value and defaults to one. It is an optional argument
1.1 Setting up Python
If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.
2. Python range() function with Examples
I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Implementation file
Add the below code to the implementation file showing the different examples of the range
method.
python-range-example.py
# python range() with examples # range() function generates the immutable sequence of numbers starting from the given number # syntax - range(start, stop[, step_size]) # where, # start is the lower limit and defaults to 0. # stop is the upper limit that generates the numbers up to the specified # example 1 # range(stop) print('Output of example 1') for i in range(10): print(i, end=' ') print('\n\n') # example 2 # range(start, stop) print('Output of example 2') for i in range(1, 20): print(i, end=' ') print('\n\n') # example 3 # range(start, stop, step_size) print('Output of example 3') for i in range(1, 20, 2): print(i, end=' ') print('\n\n') # example 4 # range with negative step size print('Output of example 4') for i in range(20, 1, -2): print(i, end=' ')
3. Code run & demo
Run this python script and if everything goes well the output will be shown in the IDE console describing the range()
method implementation.
App run
Output of example 1 0 1 2 3 4 5 6 7 8 9 Output of example 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Output of example 3 1 3 5 7 9 11 13 15 17 19 Output of example 4 20 18 16 14 12 10 8 6 4 2
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
4. Summary
In this tutorial, we learned about the range() methods and different implementations which we can use to play. You can download the source code of this tutorial from the Downloads section.
5. Download the Project
This was a tutorial on how to use range() method in python programming.
You can download the full source code of this example here: Python range() function