In a post this week, while discussing control flow in python, I wrote about repetitive control structures in python which consist of the python while and for loops. But I received some text message where a reader said my post was not concise enough; that I left off some features of python loops. I agreed with him. This was because my focus was just in showing how control structures work in python and not on showing all the features of python loops. So, in this post, I have decided to write a concise guide on python loops.
As I said earlier in the other post, when you want to repeatedly iterate over some block of code you use loops. In python, you can either use a python for loop or a python while loop. After showing examples of both loops, I will then concisely explain what situations both loops can be used that makes them similar and different.
The python for loop
In order to be more concise and cover all situations, I will use the syntax of the documentation reference in defining a python for loop.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
This python for loop syntax states that a for loop is denoted by the “for” keyword. Also, on evaluation of the iterable that would be used in the for loop, expression_list, an iterator is created consisting of all the items to be used in the looping construct. Then for each iteration, the target_list is bound to each of the items in the expression_list iterator, and it will be used in the suite which is the block of code that is to be repeated. A python for loop can have an optional else clause. The else clause, when denoted, is called when the loop has completed all its iterations.
Now a picture is worth a thousand words. Let’s illustrate the syntax above with an often used syntax:
# please note that the else clause is optional
for variable in iterable:
block of code to execute
else:
block of code when for clause ends
Just as in the documentation’s syntax, the variable is assigned each item in the iterable during an iteration until the iteration ends. Most times, the variable is used in the block of code to execute.
Let’s show how the iteration works using a python for loop example with an iterable, this time a list, and printing out each iteration of the list to show how they are passed to variable.
When you run the code above, you can see that each item in the list is printed out in the block of code. This is because for each iteration, the item variable is bound to the first fruit, then the next fruit, and so on subsequently.
What if for each iteration we want to do something with the items, like multiply each item in the sequence. Here is code that shows you how.
You can see that the python for loop iterates through each of the numbers and prints them out.
Now, let’s show how the often ignored else clause can be used. When the loop finishes its iteration we can specify an else clause with a block of code that will be executed. The else clause in a for loop is similar to the else clause in a try statement and not to the else clause in an if statement.
I told you this promises to be a concise guide. So, I will show one more example of the use of an else clause. What if we had a for loop that when a condition is satisfied, it breaks out of the loop but has to execute another block of code after it breaks out of the loop. For example, imagine having some numbers in a range, like 1 to 10, and writing a function that states whether each number is a prime or a composite. A prime does not have a factor between 2 and the number, except 1 and the number itself. So, using this property we will factor all the numbers from 2 to that number and use the result of remainder division to state whether a number is a prime or a composite. I will use two loops for this example. See how the else clause is used to achieve this effect.
Notice that the else block is triggered when the second for loop goes to completion because the number is not a composite number. Anything that is not a composite is prime. But if it is a composite number, we break out of the loop to the outer enclosing loop to start another outer iteration.
There is something I introduced in the above code which I have not talked about. That is, using the python range function in a for loop to iterate over numbers. Yes, the range and for loops come in very handy when you want to iterate over numbers in python for loops. Use them at your convenience. The syntax of a range function is: range(start, stop[, step])
. The start is the number to start the iteration from. The stop is the number at which to stop the iteration. Stop is not included in the iteration. The step signifies how you pick the numbers, maybe you want to pick every second number from the start of the range etc. When there is only one argument to the range function, it is understood to refer to the stop. The default for start, which is 0, is assumed, and the default for step, which is 1, is assumed. When there are two positional arguments, it is understood that the first is the start and the second is the stop. Then the default for the step, 1, is used. Note that you cannot make step to be zero or it will give a ValueError. To illustrate, let’s use examples.
The range function is a handy tool to use with the for loop when you are dealing with numbers. You use it to create a sequence of numbers to be used in the iteration directly, as we did in the for loop above. Or you can use it to create a set of integer indices that can be used on the sequence itself. Let’s show an example of using it to create indices for use in the iterable. Here you create the argument for the range using the length function called on the iterable. I discussed about this in an earlier post on how powerful the length function is. Now, for an example.
Item variable above are integers created by the range function as indices to the fruits list.
Finally, before I end the discussion on for loops, I have to tell you that for loops can be nested. I showed an example in the loop above that looks for prime numbers. But another example of a nested for loop would not be bad.
I promise to be concise, right? So, let’s take on python while loops.
What are python while loops?
The while loop or while statement is used for repeated execution of a block of code as long as an expression is True. Here is the syntax of a python while loop according to the documentation:
while_stmt ::= "while" assignment_expression ":" suite
["else" ":" suite]
You can see from the above that you begin the while loop with the while keyword and this is followed by the expression you want to evaluate for whether it is True or False. Note that the expression must be a Boolean expression. As long as the expression is True, the while loop will continue executing the statements in the suite or block of code. Also, notice that a while loop also has an optional else clause. This else clause can be used to signify block of code you want to run when the while loop finishes running or when the expression evaluates to false.
The common syntax for python while loop used by many authors is:
# the else clause is often not used. Optional
while condition_is_true:
body_of_code
else:
body_of_code
This is the flow of control of a while loop. First, the condition is checked whether it is True. If it is False, the while loop is not executed but flow of control moves to the next statement in the code. If the condition is True, the body of code in the while loop is executed until it becomes False.
Note that if the body of code in the while loop is executed and the condition does not become False during the time the loop is running, you will enter an infinite loop. That is, a loop that never ends. If you enter an infinite loop, just press CTRL+C on your machine and it will stop execution of the loop. But you can prevent infinite loops.
How to prevent infinite python while loops.
To prevent infinite loops occurring in your python while loops, you need to use a counter at the condition or Boolean expression. Then you have to initialize the counter before the while loop and increment or decrement the counter in the body of the loop.
Now, let’s do all this with some examples. First, showing the use of a counter in the condition of the loop to test for True.
Let’s take some points from the code above. But, first I will encourage you to run it to see that it works. First, before the loop we initialized the counter to 1, our starting number. Then we used the counter to test for the condition that we have not gone beyond the last number, 5, by saying we want counter to be true when it is less than 6. Then in the body of the while loop we incremented the counter so that on each iteration the counter keeps moving towards 5 and when it moves beyond 5 to 6, the condition becomes False so we exit out of the loop. What if we had not incremented the counter in the body of the loop? We would have entered an infinite loop. If we had not initialized the counter before the loop condition, we would have gotten a NameError exception. I want you to test these two error conditions on your own machine.
Now, if we do not want to use a counter, we could use a variable that is bound to a Boolean value in the condition of the while loop. We need to initialize the variable also before the while loop is entered. Then in the body of the while loop we change the switch for the variable so that the condition can become False when we want the loop to stop execution. Here is an example.
Notice that I am doing the same calculation but this time using a variable that is bound to a Boolean value. We initialized the variable before the while loop and makes sure it is True in the condition. Then in the body of the loop, when our condition is satisfied and we want the loop to stop execution, we switched the variable so that the condition becomes False.
There are two more statements about loops that need to be considered. The python break and continue statements. But I don’t want to repeat myself. Programmers aim to reuse code, so I would encourage you to go to the post on control flow where I discussed break and continue statements in loops. I believe I was very concise in explaining those concepts in that post. You can find the explanation at the end of the post.
Now finally, the similarities between for loops and while loops along with their differences.
Similarities and differences between python while and for loops.
First, their similarities. The basic similarity between a while loop and a for loop is that you can end either loops early via a break statement. Whenever you call a break statement on either loop, it stops execution of the loop enclosing the break statement.
There are three differences I have noticed between the two loops:
A python for loop has a finite number of iterations and you can know how many iterations it will perform. A while loop might have an infinite number of iterations and you might not be able to count how many iterations it will go through.
Although both loops can use a counter, the counter for a while loop must be initialized before the loop and then incremented or decremented in the body of the loop.
You can rewrite a python for loop using a python while loop but you might not be able to rewrite a while loop using a for loop except in some cases.
So, I can now rest in peace. That is my concise guide to loops in python.
Happy pythoning.
No comments:
Post a Comment
Your comments here!