<< Chapter < Page Chapter >> Page >

When control enters the loop, the first item in the sequence is assigned to var . Then the statements in the body of the loop are executed. Those statements may or may not refer to the contents of var , but very often will.

After that, the next item in the sequence is assigned to var and the statements in the body of the loop are executed. This process continuesuntil every item in the sequence has been processed.

After all of the items in the sequence have been processed, control transfers to the next statement following the for loop statement. (You will learn in a future module that it is also possible to have an else clause on a for loop.)

Listing 1 shows the application of a for loop to a list and then to a string extracted from the list.

Listing 1 . Application of a for loop to a list and a string.
# Illustrates the for loop #-------------------------dogs = ["Affenpinscher","Afgan Hound","Akita"] for breed in dogs:print(breed) print("Length of dogs list = " + str(len(dogs)))for letter in dogs[2]:print(letter) print(dogs[2]) #------------------------------------------------------#The output from this script is shown below. #Do not copy the following text if you copy the script.Affenpinscher Afgan HoundAkita Length of dogs list = 3A ki ta Akita

The output produced by the code in the top half of Listing 1 is shown by the bottom half of Listing 1 .

The script begins by creating and populating a list with the names of three breeds of dogs.

The first for loop in Listing 1 iterates through the list extracting and printing the name of each breed on anew line. When the first for loop in Listing 1 terminates, the code gets and prints the length of the list.

The second for loop gets and iterates through the string at index value 2 in the list ("Akita") . It prints each letter from that string on a new line. When that for loop terminates, the code in Listing 1 prints the contents of the string.

The range function

The primary for loops in many other programming languages deal strictly with numeric sequences. The built-in range function, when used with a Python for loop makes it possible to emulate that behavior.

The range function returns an immutable sequence containing a series of increasing integer values. There are two overloadedversions of the range function:

  • range(stop)
  • range(start,stop[,step])

The version with a single parameter returns a sequence containing the integers beginning with 0 and ending at one less than the value of stop . For example range(6) returns the following sequence:

[0,1,2,3,4,5]

The version of the range function with two and optionally three parameters returns a sequence that begins with start , ends just short of stop , and optionally increments by step . For example, range(1,6,2) returns the following sequence:

[1,3,5]

The sequence returned by range can be used to cause a for loop to iterate on the basis of a numeric index in much the same way that the primary for loop in C, C++, C#, and Java behaves. This is illustrated by the program in Listing 2 .

Listing 2 . Using the range function to control a for loop.
# Illustrates the for loop and the range function #------------------------------------------------sum = 0 for cnt in range(5):sum += cnt print("cnt = " + str(cnt) + ", sum = " + str(sum))print("======================") #---------------------------------------------------------------breed = "Affenpinscher" for index in range(1,len(breed),2):print("Letter at index " + str(index) + " is " + breed[index])print(breed)

The output from the code in Listing 2 is shown in Figure 2 .

Figure 2 . Output from the code in Listing 2.
cnt = 0, sum = 0 cnt = 1, sum = 1cnt = 2, sum = 3 cnt = 3, sum = 6cnt = 4, sum = 10 ======================Letter at index 1 is f Letter at index 3 is eLetter at index 5 is p Letter at index 7 is nLetter at index 9 is c Letter at index 11 is eAffenpinscher

The code in the top half of Listing 2 calls the range function to get an immutable sequence containing the integers from 0 through 4 inclusive. The for loop iterates through that sequence, extracting, summing, and printing the integer values and the sum of the values contained in the sequence.

Note that the body of this for loop contains two statements at the same indentation level.

The code in the bottom half of Listing 2 calls the range function to get an immutable sequence containing the following integers:

[1,3,5,7,9,11]

The for loop iterates through that sequence and uses the integers contained in the sequence to extract and print corresponding letters from the string"Affenpinscher".

Visualize the programs

I recommend that you create visualizations for the code in Listing 1 and Listing 2 and step through those programs one instruction at a time. As you do that, pay attention to the movements of the red and green arrows on the left,the diagram on the right, and the printed material at the bottom. That should help you to better understand the behavior of for loops both with and without the use of the range function.

Run the programs

I also encourage you to copy the code from Listing 1 and Listing 2 . Execute the code and confirm that you get the same results as those shown in Listing 1 and Figure 2 . Experiment with the code, making changes, and observing the results of your changes. Make certain that youcan explain why your changes behave as they do.

Miscellaneous

This section contains a variety of miscellaneous information.

Housekeeping material
  • Module name: Itse1359-1240-The for Loop
  • File: Itse1359-1240.htm
  • Published: 10/21/14
  • Revised: 09/05/15
Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for thismodule at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should beaware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. Ineither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please beaware that it is a copy of a module that is freely available on cnx.org and that it was made and published withoutmy prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

-end-

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Itse 1359 introduction to scripting languages: python. OpenStax CNX. Jan 22, 2016 Download for free at https://legacy.cnx.org/content/col11713/1.32
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Itse 1359 introduction to scripting languages: python' conversation and receive update notifications?

Ask