Search your course

Loops in python


 

A loop is used for iterating in data structure for example list,tuple,set or a dictionary, also loops can be utilized to iterate in strings.

 

There are two types of loops in python       

        1) For loop

        2) While loop

 

Mostly while loop is used whenever you want to execute block of code until any given condition is satisfied

 

For loop

 

below is simple demonstration of for loop to iterate in list.

 

lst = ["apples","mangoes","oranges","coconut","almonds"]
for value in lst:
    print(value)

 

For loop using range() function

 

for i in range(0,10,+2):
    print(i)
    #DO SOMETHING ELSE

 

In above script 0 is representing starting index of for loop 10 isrepresenting ending index although loop will run less then 10 times that is 9 so range will be from 0 to 9, and +2 is incremental of for loop

 

While loop

 

Basic syntax of while loop is given below

 

while condition:
    pass
    #DO SOMETHING

 

below is simple demonstration of while loop to iterate in list.

 

lst = ["apples","mangoes","oranges","coconut","almonds"]
i = 0
while i<len(lst):
    print(lst[i])
    i+=1

 

 

 

Subscribe to my youtube channel