for loop in python example programs




For loop in Python

In this post we will learn about for loop in Python. Let's start..!

[ if you don't know what is loop then click here to learn more about loop in Python. ]

for loop :

To use for loop in Python we need a keyword that is for . For loop start with keyword for then we have to specify a iterative variable. give a keyword in ; after that we have to specify a list or set or tuple or string  to iterate the values from it. You can also use range here to iterate variable in particular range.

[ if you don't know what is iteration then simply click here to learn more about iteration in Python. ]

Syntax : 

for variable in ( list, tuple, set, range, etc ) :

    for block 


for ex. Suppose you have a list having fruits name inside it. Now you want to print each fruit name one by one. For this you can use for loop. simply write a keyword for create a variable write a keyword in now specify list or write a list name; at last put a colon( : ) 

After this simply write your block. This block should be in proper indentation.


# using for loop 
fruit_list = ["mango", "apple", "cherry", "banana", "orange"]

for fruit in fruit_list:
    print(fruit)


Output :

mango
apple
cherry
banana
orange


Here we have used for keyword after that we have specify a variable named as fruit for iterating each value from list named as fruit_list then. In the block of for loop we have print the name of each fruit. 

But How for loop works ?

simply first for loop will take a value from list ( in this case 'fruit_list' ) and stores in the variable ( in this case 'fruit' ). And for loop will repeat these same steps till last value in the list.


Let's take another example of for loop using range() function.

[ if you don't know about what is range() function and how it works then Click here to learn more about range() function in Python ]


for loop with range( ) :

Syntax : 

for variable in range( parameters ) :

    for block 


for ex. Suppose you want to print 1 to 10 number. For this simply write a keyword for create a variable write a keyword in now write a function range( parameters ) and give parameter 1 , 11 ; at last put a colon( : )

After this simply write your block. This block should be in proper indentation. 


# using for loop with range() function

for number in range(1, 11):
    print(number)


Output :

1
2
3
4
5
6
7
8
9
10



This all about for loop in Python. You can use for loop in different types. Try something your own with for loop.


If you have any doubts in this post then please ask me in comment section below. I will try to solve it.


If you like these post and you have learned something from this then share this post with your friends and family.

Keep learning always.....!!! 😇😇😇




Previous Post  Next Post