Loops are another “flow control” tool, like an if statement. Loops allow you to repeat the same piece of code multiple times, which can be very useful when you are processing data.
There are two types of loops in Python, the for loop, and the while loop. The for loop is one of the easiest ways to process data. Let’s take a look:
# Define a list
a = ['test1', 'test2', 'test3']
# In the first iteration (pass through the loop)
# the value 'test1' will be assigned to the variable temp1
#
# In the second iteration, it will be assigned the value 'test2'
for temp in a:
print temp
The syntax of a for loop is as follows:
# Define a list
a = ['test1', 'test2', 'test3']
for tempVariableName in collectionToLoopThrough:
print 'do stuff here with the temp variable here'
The other type of loop is the while loop:
# Define a list a = ['test1', 'test2', 'test3'] # Loop control variable i = 0 # Store the length of the list a max = len(a) while i < max: print a[i] i += 1
The expression that follows the word while is the loop test. If true, the loop will run, and if false, it will not. The loop test is tested when the loop is first entered, and at the beginning of each iteration.
Loops in Python offer a lot of other control features, which you can read about here.
If you’ve been following the tutorials, you should have enough knowledge to learn the other features of Python on your own. If you have questions, the best place to go is either the Python documentation, especially the Python tutorial, or Google (if you wanted to write program that finds and replaces words in files in a given directory, you might search for “read file python”, “file io python”, “string replace python”).