For loop in Python

Table of content:

  1. What is a for loop and why we need it?
  2. Syntax and flowchart of for loop
  3. The range() function
  4. Nested loops.

 

  1. What is a for loop and why we need it?

For loop is a method used for iterating elements. With the help of for loop we can check the statement for all the elements one by one. It can be used for list, tuple, set, a string or a dictionary. For loop can only be applied over an iterable object.

In this code we are applying the for loop on a string. The output of this program will be:

    2. Syntax and flowchart of for loop.

Syntax of for loop in python is much similar to other languages.

In above code as we used for loop on a sequence. Here value will be each element in given sequence. Sequence can be either list, tuple or string. For each element it will check the condition till it reach to the last element.

After going through last element in sequence it will automatically break down the loop.

Flowchart of for loop:

     3. The range () function

We can generate an iterable sequence using range () function. For example, if we take a range of 5 then it will take elements as (0,1,2,3,4).

We can also define start, stop and step size also. As default step size is always 1.But this function don’t save in memory so it can be in-efficient. To improve it we can use list that will store all the elements.

 

The following program will help in getting the concept in better way.

This is a simple For loop pragram to enter the days of the week. The output of the program will be

   4.  For nested loops.

Sometimes we have to iterate through more than one sequence. For this we can use nested loops. It is loop inside a loop. We can use the for loop inside another for loop, also we can use other loops inside the for loops.

Inner loop will get executed once for each element of outer loop.

Here is a program of for loop as an example:

In this program we use the for loop to find out the Odd and Even number in a given range. The numbers are then appended in the list. The output of this program will be:

About

Codec Networks provides IT Trainings from EC Council CEH ECSA, LPT, CHFI, Network Security, Penetration Testing, ISACA, ISC2, PECB ISO 27001LA LI, Cisco Networking CCNA CCNP, Linux Administration RHCE, Prog Languages JAVA, Advanced Java, android development. We also offer B2B Industry Solutions and Services in IT | Information|Cyber Security in Delhi NCR India.

View all posts by