# 2.6 Itse1359-1240-the for loop  (Page 2/2)

 Page 2 / 2

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-

anyone know any internet site where one can find nanotechnology papers?
research.net
kanaga
Introduction about quantum dots in nanotechnology
what does nano mean?
nano basically means 10^(-9). nanometer is a unit to measure length.
Bharti
do you think it's worthwhile in the long term to study the effects and possibilities of nanotechnology on viral treatment?
absolutely yes
Daniel
how to know photocatalytic properties of tio2 nanoparticles...what to do now
it is a goid question and i want to know the answer as well
Maciej
Abigail
for teaching engĺish at school how nano technology help us
Anassong
Do somebody tell me a best nano engineering book for beginners?
there is no specific books for beginners but there is book called principle of nanotechnology
NANO
what is fullerene does it is used to make bukky balls
are you nano engineer ?
s.
fullerene is a bucky ball aka Carbon 60 molecule. It was name by the architect Fuller. He design the geodesic dome. it resembles a soccer ball.
Tarell
what is the actual application of fullerenes nowadays?
Damian
That is a great question Damian. best way to answer that question is to Google it. there are hundreds of applications for buck minister fullerenes, from medical to aerospace. you can also find plenty of research papers that will give you great detail on the potential applications of fullerenes.
Tarell
what is the Synthesis, properties,and applications of carbon nano chemistry
Mostly, they use nano carbon for electronics and for materials to be strengthened.
Virgil
is Bucky paper clear?
CYNTHIA
carbon nanotubes has various application in fuel cells membrane, current research on cancer drug,and in electronics MEMS and NEMS etc
NANO
so some one know about replacing silicon atom with phosphorous in semiconductors device?
Yeah, it is a pain to say the least. You basically have to heat the substarte up to around 1000 degrees celcius then pass phosphene gas over top of it, which is explosive and toxic by the way, under very low pressure.
Harper
Do you know which machine is used to that process?
s.
how to fabricate graphene ink ?
for screen printed electrodes ?
SUYASH
What is lattice structure?
of graphene you mean?
Ebrahim
or in general
Ebrahim
in general
s.
Graphene has a hexagonal structure
tahir
On having this app for quite a bit time, Haven't realised there's a chat room in it.
Cied
what is biological synthesis of nanoparticles
what's the easiest and fastest way to the synthesize AgNP?
China
Cied
types of nano material
I start with an easy one. carbon nanotubes woven into a long filament like a string
Porter
many many of nanotubes
Porter
what is the k.e before it land
Yasmin
what is the function of carbon nanotubes?
Cesar
I'm interested in nanotube
Uday
what is nanomaterials​ and their applications of sensors.
how did you get the value of 2000N.What calculations are needed to arrive at it
Privacy Information Security Software Version 1.1a
Good
Got questions? Join the online conversation and get instant answers!