Python for i in range | Python For Loop

Loops are an important concept not just in Python programming but in any language. It allows you to perform a certain task repeatedly.

For loop is used to iterate over elements of a sequence. It is often used when you have a piece of code that you want to repeat n number of times.

The Python range() function is used to return a sequence of numbers starting from 0 (by default if starting position is not provided) to the specified number by incrementing 1 (by default if increment value is not provided.), You can read more about Python Range here in this linked post.

Python For i in range

For i in range is a code syntax used to iterate for loops to the provided number of times through range() function. Range function is used to give the last point upto which the iteration has to go.

Syntax of range(): range(start, stop, step)

The range() function takes 3 parameters. One parameter is necessary (stop), while the other two are optional.

Here start is an optional value that you may specify to start the sequence from. The Stop value is necessary where your sequence stops. and finally, the step is the increment value which you may provide optionally for incrementing steps.

If you don’t provide the start value, by default the sequence starts from 0, similarly, if you don’t provide the step value, it increment by 1 by default.

One thing to note is that the iteration by default starts from 0 and it stops one step before the stop value. Let’s see all these from examples:

Printing numbers using iteration:

for i in range(10):
    print(i)
Output: 0
1
2
3
4
5
6
7
8
9
for i in range(5, 50, 5):
    print(i)
Output: 5
10
15
20
25
30
35
40
45

Here we have used all the parameters of the range() function where 5 is start, 50 is stop and 5 is step parameters. Let’s see another similar example:

for i in range(0, 15, 3):
    print(i)
Output: 0
3
6
9
12

Printing string using iteration:

for i in range(10):
    print('*')
Output: *
*
*
*
*
*
*
*
*
*

Some more examples of Python for i in range()

What if the start value is greater than the stop value? Let’s see:

for i in range(10, 5, -1):
    print(i)
Output: 10
9
8
7
6

for i in range(6, 5, -2):
    print(i)
Output: 6

for i in range(2 ** 2):
    print('*')
Output: *
*
*
*

for i in range(-5):
    print(i)
Output: No output, because loop will not execute

You can try all these on our Online Python Compiler

Related:

Python Basics
List, Set, Tuple, and Dictionary in Python
Python Reverse List items
Python Round() Function
Python Multiline comment
Power in Python | Python pow()
Python range() Function
Square Root in Python
Python for i in range