A Smooth Refresher on Python's Loops

I hope you are doing well with the Python smooth refreshers series. Let me quickly remind you that the aim of this series is to teach you in a smooth manner the main concepts you need to grasp in order to move forward in your Python learning journey.

Do you remember that day when you had to water 10 flowers? Or when you had to fill 20 cups of water? You were doing the same task on each flower or cup of water. Such repetition is called looping in programming. 

To give a feeling of the importance of looping, say that you were writing a program that should print the same statement 100,000 times. Would you dare repeat this statement 100,000 times, manually?! I won't, and I think you won't too. I'm sure you have much more important stuff to do. Here thus comes the beauty of looping.

Without further ado, let's see the Python way of looping.

While Loop

In this type of iteration, as long as the test is evaluating to true, the statement or block of statements keep executing. Thus, control keeps looping back to the beginning of the statement (i.e. test), and will handle control to the next statement(s) if the test evaluates to false. If the test always evaluates to true, in this case what we have is an infinite loop.

The general syntax for the while-statement is very simple, and looks as follows:

Remember the infinite loop term I mentioned a while ago? That is, the loop which never stops since the test is always true? Let's see an example of such a loop:

The value 1 is another form of the boolean value true. Thus, if you write while true, this will be equivalent to the while-statement in the example. As you will notice, you will keep getting print statements displayed infinitely. 

To terminate the loop, simply click Control-C on your keyboard. The figure below shows how the program was running infinitely and being interrupted by the keyboard (i.e. Control-C).

Im an infinite loop Ctrl-C to stop me

Let's now water our 10 beautiful flowers with Python. This can be done as follows:

The result of the program can be shown in the following figure:

Water the flower 10 times

Before moving forward, let me clarify some points in the above Python script. You may be wondering what str() is and why we have used it here. Based on the documentation:

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.

In other words, str() will return a printable string representation of the object. But, why? Let's see what Python would complain if we didn't use str():

So, the issue is that a str cannot be concatenated with int

The other point I want to mention is the use of flowers = flowers + 1. If we didn't use such a statement, we would have an infinite loop where the value of flowers would remain 1, and thus always less than 10 (always true).

For Loop

The for-loop is an iteration that steps through the items of an ordered sequence such as lists, dictionary keys, tuples, strings, etc.

The Python for-loop syntax looks as follows:

Where var will hold the items of the sequence (i.e. list, tuple) that the for-loop will be iterating through, such that the for-loop body will be executed for each item in the sequence.

Time for some examples on the for-loop!

What happens if we initialize counter = 1? In this case, you will get the error shown below since at one point in the loop the index will be out of the list range:

A small quiz. What would be the output of the following loop? (hint: remember that Python starts counting from 0):

Statements Used in While and For Loops

The subsections below will show some statements that are frequently used within loops.

break

The statement break causes the loop to terminate, and program execution is continued on the next statement.

An example of using break is shown below. It shows how the program quits (break) the loop when the if-statement evaluates to true.

continue

This statement returns control back to the beginning of the loop, ignoring any statements in the loop coming afterward. Let's see the following example:

Did you figure out how continue works? What do you think the output of this Python script would be? Go ahead, give it a try.

pass

This statement is a bit tricky. The pass statement is a null statement, that is it doesn't do anything. But, why do we use it? Suppose you were writing a program, and at some point you weren't sure what should go in the for-statement for instance, as follows:

If you try to run the program, you will get the following error:

So Python complains that there should be some statement going inside the for-loop. If you type pass in the for-loop, the output of the program will be:

From this, we can conclude that pass acts as a placeholder to allow the program to run even if you didn't decide yet what required statement(s) has to go in some place of the code.

else

The else statement is self-explanatory, and will simply contain a block of statements to run when the loop exits in a normal way, and not by a break. An example of its use is as follows:

Conclusion

To conclude this article and to imagine the importance of looping, I remember when I had to perform those image analysis operations on each pixel of an image. 

Doing this on an image with size 256x256 only means that I had to repeat the operations 65,536 times (which is the number of pixels)! Looping to the rescue!

Tags:

Comments

Related Articles