For Loop – Python Programming
We have already discussed the while loop in our previous article. In this article, we will be covering the for loop. The for loop is one of the most widely used loops in programming. As you begin writing real code, you will find that you will almost always use for loop instead of while loop. Let us now have a look at it.
Printing numbers up to 10
We are going to solve the same old problem, let us see how for loop can be used to print numbers from 1 to 10. You know the drill, re-create the code below.
It doesn’t get any simpler. There are literally just 2 lines. The first line uses the for keyword. So our code for i in range(1,10) simply tells python to loop with the condition that i is in the range of 1 to 10. Here we have used the range function. This means that that the initial value of I will be 1 and the last value of i will be 9 (10-1). Also, the for loop will automatically increment the value of I with each iteration. Inside out indented block, we’ve simply written a print function. The output for the same should be as follows.
Looping characters in a string
What is a string? A string is simply a list or array of characters. The position of each character in such a list comes after the previous character. Since these positions are numerical, strings are iterable. Let us take the name of our site and try to print each character on a different line. The code for the same is as follows.
You can see in the code above, that we just created a variable and in the for loop we have written for i in site_name. If you recall from the article about operators, we have used the in membership operator here. Python is a high-level and dynamic language. Hence we are able to loop through a string with such ease. It is important to note that not all languages have this feature. The output for the same is as follows.
For loop is very useful in iterating over a range of numbers and list of items. It is one of the most widely used loops in general. If you have any question regarding the usage of for loops, do let me know in the comment section below.