Loops In Python



Loops in Python:

A loop statement allows us to execute a statement or group of statements multiple times.



Python has two loop commands:
For loop.
While loop.

For loop:

          For loop is used for iterating over a sequence i.e lists, tuples, sets, dictionary etc.
By using range and xrange function we can iterate over the numbers in for loop.

Syntax of for loop:

             for value in sequence:
                 Body of for

Here value is the variable that takes the value of the item inside each iteration. Loop statement runs until the loop reach to the last item in the sequence. Body of the for loop is separated from the rest of the code using indentation.     

Flow chart of for loop:       




For eg.




Range Function in for loop:

We can generate specific numbers by giving range i.e range(5). Here loops run from 0 to 4.
We can also define the start, stop and step range(start, stop, step). step defaults to 1 if not provided.


        

While loop:


        while loop executes as long as the given condition is true.

Syntax of while loop:

                 while condition:
                          statement

Flow chart of while loop:




For eg.

i = 1
while i < 6:
  print(i)
  i += 1


       


Post a Comment

0 Comments