Hour 7. Learning About Loops
What You’ll Learn in This Hour:
How to perform repetitive tasks
How to use the for loop
How to use the while loop
How to use nested loops
In this hour, you will be learning about additional structured commands that help you reach your
script’s goals using Python. Specifically, the focus is on repetitive tasks and what constructs are
needed to accomplish those tasks.
Performing Repetitive Tasks
One of the great benefits of using a computer is that it doesn’t get bored performing a task over and
over again. Doing a task over and over again is called repetition.
A synonym for repetition is iteration. In the programming world, iteration is the process of
performing a defined set of tasks repeatedly until either a desired result is achieved or the set of tasks
has been performed a desired number of times.
When referring to a loop in Python, the term iteration is used. One time through a loop is called one
iteration. Going through a loop multiple times is referred to as iterating through the loop. Now, just
iterate through these last three paragraphs again and again, until you reach the desired result of
understanding the iteration terms.
Using the for Loop for Iteration
In Python, the for loop construct is called a “count-controlled” loop, because the loop’s set of tasks
will be performed a set number of times. If you want a set of tasks to be performed five times, you
can use a for loop in Python to accomplish this task.
The syntax structure of the for loop in Python is as follows:
Click here to view code image
for variable in data_list:
set_of_Python_statements
Notice in the for loop structure that there is no ending statement. In some programming or scripting
languages, you see a “done” or “end” type of statement. In a for loop, the Python statements to be
included are indented under the for construct. This is similar to the if-then statement structure.
By the Way: Indentation in Loops
Just as with the if-then statements you learned about in Hour 6, “Controlling Your
Program,” the Python statements have to be indented to be part of a loop. Remember
that in IDLE, the development environment editor does this for you automatically.