<< 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-

Questions & Answers

how does Neisseria cause meningitis
Nyibol Reply
what is microbiologist
Muhammad Reply
what is errata
Muhammad
is the branch of biology that deals with the study of microorganisms.
Ntefuni Reply
What is microbiology
Mercy Reply
studies of microbes
Louisiaste
when we takee the specimen which lumbar,spin,
Ziyad Reply
How bacteria create energy to survive?
Muhamad Reply
Bacteria doesn't produce energy they are dependent upon their substrate in case of lack of nutrients they are able to make spores which helps them to sustain in harsh environments
_Adnan
But not all bacteria make spores, l mean Eukaryotic cells have Mitochondria which acts as powerhouse for them, since bacteria don't have it, what is the substitution for it?
Muhamad
they make spores
Louisiaste
what is sporadic nd endemic, epidemic
Aminu Reply
the significance of food webs for disease transmission
Abreham
food webs brings about an infection as an individual depends on number of diseased foods or carriers dully.
Mark
explain assimilatory nitrate reduction
Esinniobiwa Reply
Assimilatory nitrate reduction is a process that occurs in some microorganisms, such as bacteria and archaea, in which nitrate (NO3-) is reduced to nitrite (NO2-), and then further reduced to ammonia (NH3).
Elkana
This process is called assimilatory nitrate reduction because the nitrogen that is produced is incorporated in the cells of microorganisms where it can be used in the synthesis of amino acids and other nitrogen products
Elkana
Examples of thermophilic organisms
Shu Reply
Give Examples of thermophilic organisms
Shu
advantages of normal Flora to the host
Micheal Reply
Prevent foreign microbes to the host
Abubakar
they provide healthier benefits to their hosts
ayesha
They are friends to host only when Host immune system is strong and become enemies when the host immune system is weakened . very bad relationship!
Mark
what is cell
faisal Reply
cell is the smallest unit of life
Fauziya
cell is the smallest unit of life
Akanni
ok
Innocent
cell is the structural and functional unit of life
Hasan
is the fundamental units of Life
Musa
what are emergency diseases
Micheal Reply
There are nothing like emergency disease but there are some common medical emergency which can occur simultaneously like Bleeding,heart attack,Breathing difficulties,severe pain heart stock.Hope you will get my point .Have a nice day ❣️
_Adnan
define infection ,prevention and control
Innocent
I think infection prevention and control is the avoidance of all things we do that gives out break of infections and promotion of health practices that promote life
Lubega
Heyy Lubega hussein where are u from?
_Adnan
en français
Adama
which site have a normal flora
ESTHER Reply
Many sites of the body have it Skin Nasal cavity Oral cavity Gastro intestinal tract
Safaa
skin
Asiina
skin,Oral,Nasal,GIt
Sadik
How can Commensal can Bacteria change into pathogen?
Sadik
How can Commensal Bacteria change into pathogen?
Sadik
all
Tesfaye
by fussion
Asiina
what are the advantages of normal Flora to the host
Micheal
what are the ways of control and prevention of nosocomial infection in the hospital
Micheal
what is inflammation
Shelly Reply
part of a tissue or an organ being wounded or bruised.
Wilfred
what term is used to name and classify microorganisms?
Micheal Reply
Binomial nomenclature
adeolu
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

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