Tutorial - Python 3 basics
For loop

Posted September ..., 2018 by Rokas Balsys



In previous tutorial we learned about While loop. In this tutorial we'll discuss about very similar topic - For loop. For loop has the ability to iterate over the items of any sequence, such as a list or a string.


Syntax:
for numbers in sequence:
   statements(s)

If a sequence contains an expression list, it is evaluated at first. Then, the first item in the sequence is assigned to the iterating numbers. Next, the statements block is executed. Each item in the list is assigned to numbers, and the statement(s) block is executed until the entire sequence is exhausted.

Example:

for letter in 'Python':
   print ('Current Letter :', letter)

Above example will print each letter in new line from word "Python".

Here's is another example of a for loop, where we take a list of fruits:

FruitList = ["Apple", "Avocado", "Banana", "Blackberry", "Blueberry", "Lemon", "Mango"]

for x in FruitList:
    print(x)

In a print Shell this code will print out each item in that list:

Apple
Avocado
Banana
Blackberry
Blueberry
Lemon
Mango

Also we could use range function within for loop:

for x in range(20,41):
    print(x)

Above code works as a generator function, and is highly efficient. It works very much like the counter (counter = counter +1) function we made with a while loop. But this one is much faster and more efficient in many cases. Of course you should use it with other purpose than just print numbers.


That's it with for loop, it's not that difficult. Now you can move to next tutorial: