top of page

PYTHON CODE: FOR LOOP Statement | Python

Loops are traditionally used to run a block of code repeatedly for a certain number of times or until the condition is met. The syntax of constructing FOR LOOP in Python is different but the idea behind it is similar to any other programming language. Here, the FOR LOOP statement iterating over a sequence, such as list or a string, executing the block of code each time.


Let us understand FOR LOOP with a basic example-

Suppose, you have a list containing names, of weekdays from Monday to Sunday, and you want to print each element of the list separately. One way to do that is by using the 'print()' command for each of the element which you want to print, as shown below-

weekdaysList = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

print (weekdaysList[0])
print (weekdaysList[1])
print (weekdaysList[2])
print (weekdaysList[3])
print (weekdaysList[4])
print (weekdaysList[5])
print (weekdaysList[6])

This approach works but is little cumbersome because we have to repeat the 'print()' command for each of the element. This is certainly not efficient approach to perform if the list has huge number of elements. Instead, we can use a statement called FOR LOOP.


The FOR LOOP begins with the keyword "for" followed by the function name defined by the programmer (in our example, "eachItem"). The code is basically saying- for 'each element' in the existing list 'do something' and that something will be defined in the next intended line (in our example, 'print()' command).

for eachItem in weekdaysList:
  print (eachItem)

The idea here is to print each element available in the list ("weekdaysList") one by one by running a FOR LOOP statement. You can also provide multiple commands below the FOR LOOP statement. Suppose, we want to print each element twice with " x2" phrase included with the repeated element. So we write another 'print()' command as shown below-

for eachItem in weekdaysList:
  print (eachItem)
  print (eachItem + " x2")

In this way, one can use the FOR LOOP statement to repeat the same code a number of times. This number of times could be specified by the programmer to a certain number, or could be defined by a certain condition being met. In our case, we have not specified the number of times it should run, instead we have defined the condition which is referring to the number of elements available in the list.

 

Disclaimer: We, in our example, only cover how to perform such functions and less focusing on the type of example we take. Our motive is to deliver the exact solution to the queries on "How To" in the most simplest way. Of course, the application of these function can be seen in our advanced modules with more complex examples and datasets.

 

Feel free to share your views and ask for models in the #comment section. If you like our content, please hit a #like button.

56 views0 comments
bottom of page