How to Use For Loop in Python

Posted on

Introduction

This is an additional article where the main focus is just to describe further the usage of the ‘loop’ reserved keyword for performing loop functionality in Python programming language. So, in the previous article is showing pseudo code, scenario and also an example using the ‘for’ loop. That article exist in this link with the title of ‘How to Loop in Python’.

How to use for loop in Python

Before going on to the further discussion, there are certain pattern for using the ‘for’ loop. In other words, there are several patterns exist for the ‘for’ loop. Those patterns exist as the for loop for iterating collection data type, string, range along with several modifications of it. In other words, the ‘for’ loop have the ability to iterate or to repeat the process using any kind of sequence available for the number of times of the loop. The sequence itself can be collection data type, string and also a range of number. Before going on to the discussion of each sequence which is compatible with the ‘for’ loop, the following is the syntax for the ‘for’ loop :

for value in sequence:
    statement;

How to use for loop with list as a sequence in Python

This part is focusing on how to use the ‘for’ loop with list as its sequence. It is actually possible to use list as a sequence. Especially if the process is actually have something to do with the list. For an example, it is exist in the following one :

C:\>python
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list_example = [1,2,3,4,5,6,7,8,9,10];
>>> sum = 0;
>>> for x in list_example:
... sum += x;
>>> print(sum);
55
>>>

In the above example, there is a list with the name of list_example. The loop or the iteration with for reserved keyword is using list collection data type as the sequence. It is automatically defining the start and the end for defining the number of times to repeat the process. Since it has 10 data, the process will be executed for 10 times. But inside the for block, the process is only showing how to sum all of the data exist in this link. The result of the summing all the data exist in the list is 55 according to the output above.

One thought on “How to Use For Loop in Python

Leave a Reply