Repetition in Python: Loops in General

The concept of a loop in a programming language has been discussed for many years and has a large degree of both theory and practice underlying it. The original loop was a branch or goto, where the top of the loop was identified with an address or label and at the bottom there was a statement that said to “go to” or transfer control to that location. Examples of this are as follows:

Branches were typical of assembly language programming, where each line of code was one actual computer instruction. The goto statement was introduced in the first real programming language FORTRAN, but was quickly supplement­ed by a more structured loop construct, the do statement. Both branch and goto statements can be conditional.

Various kinds of loop have been developed over the years, and the most com­monly used variation is the while loop. Theory says that the only kind that is needed, and probably the most general, is the loop statement as defined in the Ada language. It is essentially an infinite loop that allows escapes at multiple and various points on specified conditions. The basic syntax is as follows:

loop

exit when conditionl;

Statements …

exit when condition2;

end loop;

An exit at the top of the loop is a while loop. An exit at the end could be a re­peat … until as in Pascal or C++, and it is a simple matter to declare and initial­ize a control variable and test the condition to implement a for loop. Everything is possible with this loop syntax.

When specifically using Python, a while loop is all that is needed. If the range is an integer one, then the loop is as follows:

for i in range (a .. b):

is the same as the loop

i = a

while i < b:

i= i + 1

This loop has an initialization, a condition, and an increment. As individual entities these are somewhat hidden in Python, being masked by the syntax, but the loop control variable takes on the first value the first time the loop is executed (initialization), iterates through the selections (increment), and terminates after it selects the final one (condition). The loop control variable is not really what gets incremented; what is incremented is a count that indicates which of the items in the tuple is currently being used. In the loop:

for i in (“red”, “yellow”, “green”):

the variable i takes on the values “red”, “yellow”, and “green”, but what gets incremented each time through the loop is an indication of which position in the tuple is represented by i. The value “red” is 0, “yellow” is 1, and “green” is 2 and a count implicitly starts at 0 and steps until 2 assigning values to i. This kind of loop is similar to that found in the language PHP, and is a level of abstraction above those in Java and C++.

 

Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *