For loops in Python - How does it work.

 For loop in Python

Learn For loop in Python


For loops in Python are useful tool which allows iterate and repeat operations. 

 

What is for loop

A for loop is a control flow statement to iterate over a sequences such us: list, dictionary, tuple, string or set.

What is the for loop for

"For" loop allows you to repeat a specific block of code.
 

Examples of using fol loop:

Print every element in a list.

animals = ["cow", "chicken", "sheep", "horse", "goat"]
for
element in animals:
print(element)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

cow
chicken
sheep
horse
goat

 

Print numbers of specific range.

for i in range(1,11):
print(i)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

1
2
3
4
5
6
7
8
9
10
Note: Python like most other programming languages counts from 0 and ends at the end of range. To print indeed numbers from 1-10 you need t0 tell Python start and end points.
for i in range(1,11):
print(i)
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

1
2
3
4
5
6
7
8
9
10

Repeat a executing a sequence of block.

Let's say you want to print something 5 times, to do this use for loop with range() function.
for i in range(5):
print('Python is awesome')
_____________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

Python is awesome
Python is awesome
Python is awesome
Python is awesome
Python is awesome

  http://www.entertainmentearth.com/cjdoorway.asp?url=hitlist.asp?theme=Guardians+of+the+Galaxy
http://www.entertainmentearth.com/cjdoorway.asp?url=starwars.asp

/

Comments