"For" loops will "iterate" through each of the elements in a list. The example below sets "TheList" to contain some different types of plants and then prints out each of the elements of the list. The "for" statement will set the variable "Type" to the first element of the list,execute the code within the "for" loop and then repeat for each of the elements in the list. Notice that there is a colon at the end of the "for" statement and then all the code in the "loop" is indented by one space or tab.
TheList=['tree', 'shrub', 'grass', 'fern'] for Type in TheList: print(Type)
Combining lists created with the "range()" function allows you to create a "for" loop that iterates through a series of numbers. This is very common in programming. An example is:
for x in range(0,10): print(x)
You can also add the "step"
for x in range(0,10,2): print(x)
Sometimes you'll want to iterate through a list and know which index you are on. This is commonly used when you have a list of values and want to know which "row" you are on. The following will print the values and the index:
TheList= [1.5,2.3,4.5,8.3] for Index in range(len(TheList)): print(Index, TheList[Index])
When we are processing data in tables we may want to go to each row in the table and then look at each cell in each row. This requires a "for" loop to go through the rows and a "nested" "for" loop to go through each cell. Try code like the example below to see how you can "next" for loops. Use the debugger to step through this code and watch how the row will first be set to 0, then the code will go through each value of the column before moving the row to the next value. Then it will go through the column values again.
for row in range(0,10): # go through the code below for each value from 0 to 9 for column in range(0,4): # go through the code below for each value from 0 to 4 print(format(row)+","+format(column))
This approach also allows you to process raster files and other multi-dimensional datasets.
You can put "for" loops together with "if" statements to create code to process a wide variety of data sets. Try the following for fun and then change the range of values (contributed by student Lindsey D. Holmfrom http://pythoncentral.io/pythons-range-function-explained/).
for NumBeersOnWall in range(99,0,-1): if (NumBeersOnWall==1): print("1 bottle of beer on the wall, 1 bottle of beer") print("So take it down, pass it around, no more bottles of beer on the wall!") elif (NumBeersOnWall==2): print("2 bottles of beer on the wall, 2 bottles of beer") print("So take one down, pass it around, 1 bottle of beer on the wall!") else: print(format(NumBeersOnWall)+" bottles of beer on the wall, "+format(NumBeersOnWall)+" bottles of beer") print("So take one down, pass it around, "+format(NumBeersOnWall-1)+" bottles of beer on the wall!")
Python Documentation: More Control Flow Tools
© Copyright 2018 HSU - All rights reserved.