Feeling Loopy Yet?

On how to use loops in Python

It’s hard to do much coding without getting loopy. There are  reasons for that. First, we tend to use computers to do the same or similar tasks over and over, which is great because they don’t get bored (yet).

Second, loops allow your computer to go back to the same useful functions and plug in different values based on things such as input from human beings.

Third, loops help you write programs that go through long strings and lists of data one at a time (though incredibly quickly) to make decisions about them or otherwise use them.

Without loops, most programs would run for a split second and be done. So, loops are good –unless they’re bad — and when they’re bad, they can be very, very bad (play spooky foreshadowing music here).

Python has a simple and elegant loop system. There are really two kinds of loops, or three if you count nested loops (where you have loops within loops):

‘for’ loops
‘while’ loops
 nested loops

Let’s start with the “for” loops. Some programmers swear by them.  In one of the first books I read, Python in a Day, Richard Wagstaff notes, “I almost always use only the ‘for’ loop.” That’s largely because avoiding while loops reduces the risk of getting stuck in infinite loops.

“For” loops work in a number of ways. Here’s an example that uses a short list:

for number in [1, 2, 3]:
    print(number)
    print("Nobody expects the Spanish Inquisition! " * number)

Here’s what happens when you run this program:

1
Nobody expects the Spanish Inquisition!
2
Nobody expects the Spanish Inquisition! Nobody expects the Spanish Inquisition!
3
Nobody expects the Spanish Inquisition! Nobody expects the Spanish Inquisition! Nobody expects the Spanish 
Inquisition!

We multiply the number of times we say this classic Monty Python quip by the numbers in the list (oh yeah, although you probably know this already, the symbol * means multiplication in Python). When I started with Python, it took me awhile to figure out that the most important two words in such code are the most innocuous ones: “for” and “in”.  In Line 1 above, the word “number” has no particular importance. If I substituted the word “tomcat” or “aluminium” or “jigglywiggly” for the word “number,” the code would work exactly the same way. Quite often, programmers just use the letter i as the stand-in. It’s quick and dirty but definitely doesn’t stand for “imagination.”

All Python really “knows” is that you want to do something a certain number of times, depending on what’s in the list.  Think of it as your idiot savant bro, ala Rain Man. It’s excellent at counting and listing, not so hot at nuance.

Let’s put the “for” loop at the heart of a new function, like the one below. We’ll get super corny and jump with both feet into a dog metaphor.  We’ll name this function LassTheTailWagger.  We feed that function treats, which are in the parenthetical maw of our parameter. For every batch of treats she eats, she wags her tail, thus giving us the total number of all the treats.

(Note: If you try this at home, don’t forget to put the indents in the right place. They make all the difference, as we’ll see in our next post)

def LassTheTailWagger(dog_treats_she_eats):
#Returns the sum of the numbers treats eaten, according to wags of tail
    sumOfWags = 0
    for number in dog_treats_she_eats:
        sumOfWags = sumOfWags + number
    return sumOfWags

print(LassTheTailWagger([5, 3, 2, 7]))

At first, there are zero wags but, as we feed her treats, the sum of all the wags continues to climb. In the first loop, we feed her 5 treats (based on the list of numbers in the print line), and the SumOfWags equal 5. The code runs and then we loop the next number in the list (3) up into the code. It adds 5 and 3. The loop continues to run until we get to the last number in the list (7). At that point, we have fed her 17 treats and the program stops running.

If this is still confusing to you, the beginner, don’t worry about it. You’ve probably got the general idea, and it’ll become clearer as you learn more about coding in general and Python in particular. Keep in mind that playing around and repetition are the keys to learning. So, my advice is to play around with simple “for” loops for your own amusement until you’ve gotten the hang of them.

PS – If you want more tutoring on “for” loops, I recommend you try out the following: Python 3 Video Tutorial – For Loops

Featured image from Author User:Coaster J From https://commons.wikimedia.org/wiki/File:Blue_fire_loop.jpg