The last post discussed on the use of the python if else, and elif statements as part of a selection control structure. Today, the second part, we will discuss on repetition control structures using python while and for loops. These control flows are used when we want to reuse parts of some code a number of times based on a condition.
The looping constructs provided by python, the while and for loops, are distinct, yet sometimes they can be interchanged except in some cases. First, we will discuss the python while loop.
The python while loop.
A while loop helps one to carry out repeated execution of a block of code based on repeated testing of a Boolean condition.
The syntax of a while loop is as follows:
while condition:
body
Just similar to the python if statement, the condition is a Boolean expression that evaluates to True or False, and the body is a block of code. The block of code can even be nested with other control structures. The while loops starts its execution by testing the Boolean condition. If the condition evaluates to True, the body of the loop is executed. After the execution of the body, the condition is retested again. If the condition evaluates to True again, another iteration of the body is done. This iteration is repeated as long as the condition evaluates to True. The moment it evaluates to False, the loop is exited and the flow of control transfers to the statement outside the python while loop.
To make sure that the while loop doesn’t run forever, it should come to a point where the condition will evaluate to False. To do this effectively, use a counter that you initialize before the loop and that is incremented or decremented inside the loop. If on the other hand you find that you didn’t do so and your loop runs forever, just press Ctrl+C to interrupt the process.
Here is a code that loops through a list of fruits and tells us whether our favorite fruit, which we have to input, is in the list of fruits. Please, pardon me that the list of recommended fruits is short.
Notice in line 5 that the python while loop is based on two Boolean expressions:
while j < len(fruits) and fruits[j] != fav_fruit:
The first Boolean expression checks to make sure we have not gone to the end of the list and the second checks by the index, j, to see if we have the fruit in our list. After the Boolean expressions, the body of the loop is just a one-liner that increments the index to the list, j. j is being used here as an index to the list to iterate through the list whenever the Boolean expressions evaluates to True; that means we have not found a match for favorite fruit in the list. There is some python if else statements after the while loop that is used as confirmation whether a match was found or not. You can see the post on python if else statements.
This code does not run forever; it terminates no matter what the user enters. Because either we will not find a favorite fruit on the list and get to the end of the list where the loop terminates or we will find a favorite fruit on the list and the loop then terminates.
Now, let’s go to the second looping structure: python’s for loop with some examples.
The python for loop.
When you want to iterate through a sequence of elements in an iterable, the for loop is more preferred to the while loop. It can be used on any structure that is iterable, whether a sequence or collection. Sequences are python strings, tuples, range, and bytes while collections are python dictionaries, sets, and frozensets. The syntax of a python for loop is:
for element in iterable:
body
You often use the element variable in the body code; the reason why we are iterating through the iterable in the first place is to access the elements. Readers who are familiar with java programming language would realize that the python for loop is in some sense similar to the java “for each” loop.
To illustrate the way a for loop works, let us take a list of numbers, iterate through each of the numbers in the list and add them together to get a total sum.
In the code above, the variable num iterates through each of the numbers in the list of numbers in the for loop and then at the body code, it adds the numbers to total variable to give the total sum.
Let’s take another python for loop example of getting the biggest number in the list of numbers.
We first assigned biggest variable to an arbitrary number, this time 0, and then in the for loop num iterates through each of the numbers. Each time num gets the value of one of the numbers in the list. In the body of the for loop we compare num to the biggest each time and if num is bigger than the biggest, we assign that num to the biggest variable. This comparison happens each iteration through the list in the for loop.
We could achieve the above code using a while loop but we would need to use an indexing method. Indexing with for loops will be described below. But note that some collections like sets cannot be done using while loops because they cannot be indexed.
Now let’s implement a for loop using an index into the elements of the iterable.
Python for loops using an index
There are occasions where we might want to know where an element resides within an iterable. The traditional application of the for loop does not give us that benefit of location. But we can get that effect by indexing into the iterable using a python range function. The range function will generate a sequence of numbers that serve as the indices into the iterable or sequence. The syntax for the for loop is:
for element in range(len(iterable)):
body
Note how the python length function provides the number that range will use to generate the indices for looping through the iterable. I have a post on the python length function. You can check it out to further understand the syntax above. Now, let’s take some illustrative example. Suppose we want to get the biggest number like we did above but using the indices in the loop, we could implement the code this way:
We eventually implemented the same code like before but instead of iterating directly through the numbers in the list, we used the indexing method to iterate through the numbers.
Note that the index variable above is an integer which is derived from the range of values generated by the range function.
I think we have basically covered the essential points for python while and for loops. But we will not close the chapter without talking about two important statements that have an influence on the iteration of a while and for loop – the python break and continue statements.
The python break and continue statements
Both of these statements interrupt the operation of a while or for loop but in different ways.
The break statement terminates the execution of the loop and transfers control to the next statement in the code. It is usually used to check for the trigger of a condition in the loop and when that condition is satisfied, the loop is terminated.
For example, let us say we want to loop through the list of numbers above to stop when we get a 9. This is how the code could be written. Watch how the python break statement was inserted into a control flow block.
If you run the code above, you will notice that the loop is iterating through each of the numbers until it gets triggered when num is 9. When this condition is reached, the loop terminates and the rest of the numbers are not referenced.
Use the break statement sparingly. It has great power.
The companion loop interruption statement is the python continue statement. The continue statement is usually employed when we don’t want a set of statements in the body of the loop to be executed when a condition is triggered. When triggered, control passes to the next item in the loop; the loop is not terminated.
An example will suffice.
I used a python while loop this time around. The Boolean expression in the while loop checks for when we have looped through all the elements in the numbers list. For each num we are looping, we first check if the number at that index is 0, if it is not zero, we use it to divide the numerator and print out the result, but if it is zero, we tell the program to ignore that number, don’t use it to divide the numerator, and move on to the next number in the loop using the continue statement. This is a very convenient way to program. That is why I love python.
Notice on line 6 and 10 that each time I increase the index by 1 so that the loop can proceed. This makes sure we do not find ourselves in an infinite loop that doesn’t end.
Take your knowledge to new heights. Experiment with the looping constructs introduced here. It’s a joyful thing programming in python.
GOOD Post, Thanks for sharing!
ReplyDeleteDevOps Training
DevOps Online Training