How to use the Python loop range?

In Python, the range() function can be used to generate a sequence of integers that can be utilized in a loop.

The syntax of the range() function is as follows: range(start, stop, step)

Explanation of parameters:

  1. start: optional, represents the starting value of the sequence, with a default of 0.
  2. stop: mandatory, indicating the end value of the sequence (excluding that value).
  3. Step: Optional, indicating the step size of the sequence, with a default value of 1.

Here are a few examples of using the range() function for looping:

  1. Use the range() function to iterate through each element in a sequence.
for i in range(5):
    print(i)

Output:

0
1
2
3
4
  1. Set the starting value, ending value, and step size for the loop using the range() function.
for i in range(1, 10, 2):
    print(i)

Result:

1
3
5
7
9
  1. Traverse through each element in the list using the range() function along with the len() function.
my_list = ['apple', 'banana', 'orange']
for i in range(len(my_list)):
    print(my_list[i])

Output:

apple
banana
orange

In the examples above, the range() function creates a sequence of integers to loop through different values in various situations.

bannerAds