For Loops

Outside Resources:

TheNewBoston Video – for

TheNewBoston Video – while and range

w3schools – looping through a range

LearnPython.org interactive tutorial – loops

TutorialsPoint interactive tutorial – loops

Snakify.org interactive tutorial – for loop with range


For Loops Intro

Loops allow a programmer to repeat sections of code.

For Loops in Python repeat code once for every item in a list or other type of container.

Try this code:

for n in [2, 5, 7]:
    print("Here is the next number times four:")
    print(n*4)

When you run it, the program will repeat the two tabbed lines of code for every item in the list of numbers. The variable n is a walker variable. Every time the loop repeats, it becomes equal to the next item in the list. The first time through the loop, n=2. The next time, n=5, and the last time, n=7. After the third time, there are no more numbers in the list, so the loop ends.

The walker variable is a local variable that can be used inside the loop. It can be used in calculations, or printed, or used as an index of a list or string, or anything else that a variable can do.

Now try this code:

for i in range(7):
    print(i)

That type of loop is useful if you simply need to repeat code a certain number of times.

Iterating through a List

Lists (and strings) are containers, which means they can hold one or more items. A loop can iterate through any container, which means it can repeat code for every item in that container.

Next example:

cities = ["New York", "Rome", "Tokyo"]

for c in cities:
    print(c + " is a city.")
    print("This city name is " + str(len(c)) + " characters long.")

In this case, we used a list (cities) that had already been created earlier in the code. We want to do the same two lines of code for every city in the list.

I named the walker variable c since that is the first letter of “city.”

Item number or the item itself?

Try to spot the differences in the next three for loops:

cats = ['Lily', 'Snickers', 'Frank']
for c in cats:
    print(c)

for i in range(len(cats)):
    print(i)

for i in range(len(cats)):
    print(cats[i])

The middle one only prints numbers. The first and last loops produce the exact same output, but the first one has shorter code. That can be good, but if you need to use the item number in our code, you might actually prefer the last one.