Python Basic – For Loop in the Control Structure in Python

Home /

Table of Contents

Range

We have seen in the previous sections how to create a list and work with the list. I also saw the use of the while loop. In the next section, we will discuss another type of loop (for). Before that, in this section, we will talk about a widely used function called range. This function allows you to automatically create a list, the elements of which are in a certain order. Such as –

Example:

   digits_list = list(range(10))
   print(digits_list)

Output:   

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In the example above, a list comprises 10 consecutive numbers from 0 to 9. The range function is used with range because range actually returns an object and so it is converted to a usable list by sending it as an argument to the list function.

It is not always the element of range that starts from 0. Instead, you can change the range function’s argument to set the start and end limits as desired. Such as –

Example:

   digits_list = list(range(5,10))
   print(digits_list)

Output:

[5, 6, 7, 8, 9]

Here the first element of the list starts at 5 and ends at 9 because we want the value from 5 to 10. Again, this sequential pattern can also be changed by setting the third argument of the range function. That is, if we want, we can set an interval between the beginning and the end of the number so that the elements will not be a sequence but a fixed interval. Such as –

Example:

   digits_list = list(range(5, 30, 3))
   print(digits_list)

Output:

[5, 8, 11, 14, 17, 20, 23, 26, 29]

I hope you can understand the order by looking at the output.

And this way we can easily create a list using the range function. But one thing to keep in mind is that the range function will take these three parameters as arguments. There is no argument in the range function without these three. So if we want to give a fourth argument but give an error. Because the range does not expect more than three arguments.

For Loop

We have seen before how to use a while loop to perform a task more than once based on the validity of a particular condition. However, to work with any sequence-type object in Python, for example, using a while loop to work with each element of the list, you have to write a little more code. For example, let’s look at the following example to weld the concept of the while loop and understand the matter –

Example:

   skills = ["Python", "C++", "Javascript", "Matlab"]
   start_index = 0
   max_index = len(skills) - 1
 
   while start_index <= max_index: # Work until this condition is True
       skill = skills[start_index]
       print(skill + " Javascript!")
       start_index = start_index + 1

Output:

Python Javascript!
C++ Javascript!
Javascript Javascript!
Matlab Javascript!

The output is the same. So, whenever you need to work with an iterable, it is better to use for loop.

Application of for loop

Now suppose you don’t have a list but need to repeat a task a certain number of times. What to do then? A nice function for this is a range which we have seen in the previous section. Remember, lists can be arbitrarily created using range? Let’s look at the following example using this –

Example:

   for i in range(10):
       print(i)

Output:

   0
   1
   2
   3
   4
   5
   6
   7
   8
   9

That is, a hypothetical list is created using the range function whose elements ranged from 0 to 9 which is  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. And that list has been iterated with for loop, that is, this loop has been worked 10 times. And the job was to capture every element and print it.

So far we have been giving only one argument in terms of parameters in range function. When we wrote the range(10) for the loop, it basically printed from 0 to 9. Again, if I set the range(20) in the same way, I would print it from 0 to 19 in the same way. But we can customize our range if we want, for example, from 5 to 9. All we have to do is pass two values ​​or parameters in the range function, the first is the beginning and the next is the end. Notice the code below –

Example:

   for i in range(5, 10):
       print(i)

Output:

   5
   6
   7
   8
   9

We can also tell the step size here. How many cells will print the value sequentially? For this, we have to add one more parameter to the above code, which will be the interval or step size. For example, we will print from 5 to 15, and we want three cells to be printed in a row. So for this, we have to put the values ​​’start, end, step_size’ inside the range function, respectively. Notice the code below –

Example:

   for i in range(5, 15, 3):
       print(i)

Output:

   5
   8
   11
   14

Well so far we can do one thing, so far we have seen the value printed on the front because we now write a code using the range that will print the value in the opposite direction, let’s say we go from 10 to 0 and go. I also use the step size, as if the two cells print the value backward. Looking at the code below will make the point clearer –

Example:

   for i in range(10, 0, -2):
       print(i)

Output:

   10
   8
   6
   4
   2

Well, one interesting thing to note is that while working with range so far, you may have noticed that in the range function, you can only give an integer-type value, not a float-type value. In fact, the range function does not take the float type value as an argument.

But we can create custom functions for this if we want. Here we will create a user-defined function, that will work just like the range function, but the difference is that it can also work with float-type data. Well, the functions section has a detailed explanation of user-defined functions. If you are not familiar with it, first find out about it, then read it, it will help you to understand. Well, notice the code below –

Example:

   def custom_range(start, stop, step):
       i = start
       while i < stop:
           yield i
           i += step
   for i in custom_range(0.5, 2.0 ,0.1):
           print(i)

Output:

   0.5
   0.6
   0.7
   0.7999999999999999
   0.8999999999999999
   0.9999999999999999
   1.0999999999999999
   1.2
   1.3
   1.4000000000000001
   1.5000000000000002
   1.6000000000000003
   1.7000000000000004
   1.8000000000000005
   1.9000000000000006

Well, if the string is somehow iterable then let’s see if something can be done by doing a for loop here too –

Example:

   for letter in 'EnableGeek':
       print(letter)

Output:

   E
   n
   a
   b
   l
   e
   G
   e
   e
   k

For a loop like a while loop, the flow of work can be controlled using keywords like break, continue, etc. Such as –

Example:

   for i in range(20):
       if i == 5:
           continue
       if i > 9:
           break
       print(i)
 
   print("Printed first 10 numbers except 5!")

Output:

   0
   1
   2
   3
   4
   6
   7
   8
   9
   Printed first 10 numbers except 5!

A list/range with these 20 elements from 0 to 19 above has been worked on but when 5 elements were found (via i ) it was avoided without printing using continue ( flipped at the beginning of the loop ). Again, when the element is greater than 9, then the work of for loop has been stopped by break statement, due to which no work of for loop is seen after 9 prints, but the execution of a simple print statement at the end of the program.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article