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

What are the factors that affect demand for a commodity
Florence Reply
differentiate between demand and supply giving examples
Lambiv Reply
differentiated between demand and supply using examples
Lambiv
what is labour ?
Lambiv
how will I do?
Venny Reply
how is the graph works?I don't fully understand
Rezat Reply
information
Eliyee
devaluation
Eliyee
t
WARKISA
hi guys good evening to all
Lambiv
multiple choice question
Aster Reply
appreciation
Eliyee
explain perfect market
Lindiwe Reply
In economics, a perfect market refers to a theoretical construct where all participants have perfect information, goods are homogenous, there are no barriers to entry or exit, and prices are determined solely by supply and demand. It's an idealized model used for analysis,
Ezea
What is ceteris paribus?
Shukri Reply
other things being equal
AI-Robot
When MP₁ becomes negative, TP start to decline. Extuples Suppose that the short-run production function of certain cut-flower firm is given by: Q=4KL-0.6K2 - 0.112 • Where is quantity of cut flower produced, I is labour input and K is fixed capital input (K-5). Determine the average product of lab
Kelo
Extuples Suppose that the short-run production function of certain cut-flower firm is given by: Q=4KL-0.6K2 - 0.112 • Where is quantity of cut flower produced, I is labour input and K is fixed capital input (K-5). Determine the average product of labour (APL) and marginal product of labour (MPL)
Kelo
yes,thank you
Shukri
Can I ask you other question?
Shukri
what is monopoly mean?
Habtamu Reply
What is different between quantity demand and demand?
Shukri Reply
Quantity demanded refers to the specific amount of a good or service that consumers are willing and able to purchase at a give price and within a specific time period. Demand, on the other hand, is a broader concept that encompasses the entire relationship between price and quantity demanded
Ezea
ok
Shukri
how do you save a country economic situation when it's falling apart
Lilia Reply
what is the difference between economic growth and development
Fiker Reply
Economic growth as an increase in the production and consumption of goods and services within an economy.but Economic development as a broader concept that encompasses not only economic growth but also social & human well being.
Shukri
production function means
Jabir
What do you think is more important to focus on when considering inequality ?
Abdisa Reply
any question about economics?
Awais Reply
sir...I just want to ask one question... Define the term contract curve? if you are free please help me to find this answer 🙏
Asui
it is a curve that we get after connecting the pareto optimal combinations of two consumers after their mutually beneficial trade offs
Awais
thank you so much 👍 sir
Asui
In economics, the contract curve refers to the set of points in an Edgeworth box diagram where both parties involved in a trade cannot be made better off without making one of them worse off. It represents the Pareto efficient allocations of goods between two individuals or entities, where neither p
Cornelius
In economics, the contract curve refers to the set of points in an Edgeworth box diagram where both parties involved in a trade cannot be made better off without making one of them worse off. It represents the Pareto efficient allocations of goods between two individuals or entities,
Cornelius
Suppose a consumer consuming two commodities X and Y has The following utility function u=X0.4 Y0.6. If the price of the X and Y are 2 and 3 respectively and income Constraint is birr 50. A,Calculate quantities of x and y which maximize utility. B,Calculate value of Lagrange multiplier. C,Calculate quantities of X and Y consumed with a given price. D,alculate optimum level of output .
Feyisa Reply
Answer
Feyisa
c
Jabir
the market for lemon has 10 potential consumers, each having an individual demand curve p=101-10Qi, where p is price in dollar's per cup and Qi is the number of cups demanded per week by the i th consumer.Find the market demand curve using algebra. Draw an individual demand curve and the market dema
Gsbwnw Reply
suppose the production function is given by ( L, K)=L¼K¾.assuming capital is fixed find APL and MPL. consider the following short run production function:Q=6L²-0.4L³ a) find the value of L that maximizes output b)find the value of L that maximizes marginal product
Abdureman
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