Tutorial - Python 3 basics For loop

This tutorial is about Python while loop, short basic introduction with while loop syntax and what is infinite loop.

In the previous tutorial, we learned about the While loop. In this tutorial, we'll discuss a 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)

The above example will print each letter in a new line from the 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)

The 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 for other purposes than just print numbers.


That's it with for loop, it's not that difficult.