Comprehensive Python

Table Of Contents:

Python Loops

Hello once again, I welcome you all to the other part of our programming series. Here, ladies and gentlement, we will be looking at python loops:
Let's begin by considering what the heck is loop.

What is a loop: Simply put, a loop is a block of code that keeps repeating itself, so long as it remains uninterrupted.
A loop is interrupted by keyboard key sequences - Most common being CTRL + C and when a result of a test turns false.
All this doesnt make sense for now, but do not be disgraced. There are two loops in python. For and While.

The FOR Loop
In python, for loop is commonly used type of loop, which repeats a block of code as long as there is a next item in a collection (Lists, Dictionaries, Sets, Tuples). Every time a for loop executes, a count of one in the number of items will be deducted, and if the loops executes the same times as the items in the collection, then the test will return False , resulting in a loop being interrupted and not execute an attached block.
In python, a loop, just like in Program Flow Controls' if, has the following syntax:
>>> for test :
...    # your block here
...    # another block here

If you notice well, you will know that the block after the for test is indented inside the for itself and not on the same column.
All the blocks covered by for must start on the same column but not same column as for itself.

The test part is the test of items in a collection.
The commonly used test cases for collection are membership operators we saw ealier in the operators section.
Taken we have a collection of people as people = ["Amin", "John", "George"], and we want to print this using python, then this is what we would normally do:

>>> people = ["Amin", "John", "George"]
>>> print(people[0]) # Amin
>>> print(people[1]) # John
>>> print(people[2]) # George

You can see on the above code that the print keeps repeating inconveniently.
What if we have 100 items in the collection, what about 1000 would you manage to type all those prints? obviously "NO!".
To solve this, then that's where for look comes in play, and using for loop, this is what we would do:

>>> people = ["Amin", "John", "George"]
>>> for person in people:
...    print(person)
... # Amin, John, George

In the above program, that is enough code to print however much the items in the list, so simple huh?
This means, we are taking each item in the collection and set it to a placeholder variable (person), and check if that thing is available in the list.
In our case, it will loop through all the items and as all are available, it will print them one by one. When all the items are cycled, then the loop will stop automatically, as there is nothing remaining to check in the list.

The WHILE Loop

Now that we've seen what a for loop is capable of doing, here we will see what a while loop brings to the table. Just like a for loop, this loop also has the same format, a while itself, then a test, then ":" and finally the block.
This loop, unlike for loop, and unless otherwise, is not used to iterate through a collection of items.
This one is used to test the truthfullness of a test, more often used to create infinite loops:
Consider the following code:

>>> people = ["Amin", "John", "George"]
>>> count = 0
>>> while count < len(people):
...    print(people[count])
...    count += 1

and the results will be:

        Amin
        John
        Jane
    

You should take a deep look here. The loop begins by testing if count, which in this case we set to zero (0) is not bigger than the number of people (length of people variable).
In this case it is true, as 0 can not be bigger than 3 (number of people). so the block will execute and print a person on 0. people[0] which is Amin.

Then the count will be incremented (look on increment operators) by 1, which will resume the loop again.
The test will happen again, and now count is 1, which is still not bigger than 3, so the process will repeat and person on people[1] will be printed and count incremented again, untill it gets to 2. 2 is still not bigger than 3 so the item on index 2, people[2], will be printed which in this case happens to be the last item and the count will be incremented to 3.
Now 3 is not less than 3 so the test will fail, which will result the loop to be interrupted (terminated).

Beware with the loops that keep passing the test (returning True) on the test as it executes forever and results into memory errors (Stack Full).

Another thing to note is that you can use at the end of each loop, an else statement. This will execute when the loop finish as default.

>>> people = ["Amin", "John", "George"]
>>> count = 0
>>> while count < len(people):
...    print(people[count])
...    count += 1
... else:
...    print("All people printed")

A Loops lesson is never complete without mentioning: continue and break.
This phrases help a developer to have the control of the loop, as to when it terminates, or when it jumps something.
As the phrase can be translated, break will cause the loop to terminate prematurely, and continue will cause a loop to ignore the rest of the loop's break from where it happens. Care must be taken as to use programs control (Tests) before deciding to use these two phrases.

Consider the following code

>>> people = ["Amin", "John", "George"]
>>> count = 0
>>> while count < len(people):
...    print(people[count])
...    break
... else:
...    print("All people printed")

In this program, the loop will execute, and print the first person, and then it meets a giant break, then the loop will terminate without printing all the rest.
This will cause the result become:

        Amin
    

Instead of terminating the loop, continue will merely cause the loop to jump the rest of the code (block) down the continue keyword.

In either case, there is a high probability that you will need a test to see if the loop has reached some item/point before breaking/jumping.

Proud to say that this marks the end of our today's tutorial, see you in the next lesson.