Python For Loop and Range Function

We can use the PyCharm code editor for this example. If you do not know about it then follow this link- How to install PyCharm for Python and create a program in it.

Python For Loop:

The for loops are used to execute repetitive tasks. A for loop will take a range of values as an argument and assign them one by one to a variable. The block of code will be executed once for each variable. The for loop is also used to work with objects that are iterable, such as sequences. So, with the help of this loop, you can iterate over each element that exists in a sequence of collections, get one element at a time and execute the code for that element.

flow chart of for loop

The Range() Function:

The range() is a built-in function in Python. It is used to create a list containing a sequence of integers from the given start value upto stop value (excluding stop value), with a difference of the given step value. To begin with, simply remember that function takes parameters to work on. In function range(), start, stop and step are parameters. The start and step parameters are optional. If the start value is not specified, by default the list starts from 0. If the step is also not specified, by default the value increases by 1 in each iteration. All parameters of the range() function must be integers. The step parameter can be a positive or a negative integer excluding zero.

Range() Function Example:

(1) range(5)

start = 0
condition < 5
increment 1
range function = 0, 1, 2, 3, 4
range with 5 in python

(2) range(1, 6)

start = 1
condition < 6
increment 1
range function = 1, 2, 3, 4, 5
range with 1,6 in python

(3) range(1, 6, 2)

start = 1
condition < 6
increment 2
range function = 1, 3, 5
range 1,2,6 in python

(4) Range Function Reverse case:

  • range(5, 0, -1)
range reverse example in python
  • range(8, 0, -2)
range reverse case in python
  • range(20, 3, -4)
range reverse code in python

(5) Example- Create a table of 4 using for loop and range function.

for with range function to create table in python

Tutorial Python
Tutorial MySQL
Natural Language Processing (NLP)
What is Virtual Reality?
Spooling and Virtual Devices
Operating System as a Resource Manager
Linux- Features, and Benefits
Python (programming language)– Wikipedia

Comments (No)

Leave a Reply