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


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:


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:


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.


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

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.


Questions & Answers

anyone know any internet site where one can find nanotechnology papers?
Damian Reply
Introduction about quantum dots in nanotechnology
Praveena Reply
what does nano mean?
Anassong Reply
nano basically means 10^(-9). nanometer is a unit to measure length.
do you think it's worthwhile in the long term to study the effects and possibilities of nanotechnology on viral treatment?
Damian Reply
absolutely yes
how to know photocatalytic properties of tio2 nanoparticles...what to do now
Akash Reply
it is a goid question and i want to know the answer as well
characteristics of micro business
for teaching engĺish at school how nano technology help us
Do somebody tell me a best nano engineering book for beginners?
s. Reply
there is no specific books for beginners but there is book called principle of nanotechnology
what is fullerene does it is used to make bukky balls
Devang Reply
are you nano engineer ?
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.
what is the actual application of fullerenes nowadays?
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.
what is the Synthesis, properties,and applications of carbon nano chemistry
Abhijith Reply
Mostly, they use nano carbon for electronics and for materials to be strengthened.
is Bucky paper clear?
carbon nanotubes has various application in fuel cells membrane, current research on cancer drug,and in electronics MEMS and NEMS etc
so some one know about replacing silicon atom with phosphorous in semiconductors device?
s. Reply
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.
Do you know which machine is used to that process?
how to fabricate graphene ink ?
for screen printed electrodes ?
What is lattice structure?
s. Reply
of graphene you mean?
or in general
in general
Graphene has a hexagonal structure
On having this app for quite a bit time, Haven't realised there's a chat room in it.
what is biological synthesis of nanoparticles
Sanket Reply
what's the easiest and fastest way to the synthesize AgNP?
Damian Reply
types of nano material
abeetha Reply
I start with an easy one. carbon nanotubes woven into a long filament like a string
many many of nanotubes
what is the k.e before it land
what is the function of carbon nanotubes?
I'm interested in nanotube
what is nanomaterials​ and their applications of sensors.
Ramkumar Reply
how did you get the value of 2000N.What calculations are needed to arrive at it
Smarajit Reply
Privacy Information Security Software Version 1.1a
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get the best Algebra and trigonometry course in your pocket!

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?