In our previous lecture, we learned about while loops in Python, now let us check ‘for loops in Python’. Aim of ‘for’ loop is same as that of while loop. However, for loop is used to iterate over a particular sequence or order. This loop can iterate over string, list, tuple, range and many more.
for variable in sequence: Statements
for variable in range(0, req_itr): Statements
Let’s understand the working of for loop with the help of an example :
Program : To traverse a given list of items.
# for loop illustration planets = ['mercury', 'venus', 'earth', 'mars'] for each_planet in planets: print(each_planet, end=' ')
Here, variable ‘each_planet’ is acting as a list element.
Above code can be written using range() function as well.