The Personal Web Pages of Chris X. Edwards

XED's Python Lessons for Beginners

--------------------------

Lesson Seven - Re: Iterating, Another Loop

If you want something to happen three times, you could use the `while x < 3:` strategy shown in the last lesson. This would work, and although it's not too difficult, there are often easier ways to do this kind of thing in Python. More importantly, there are ways of handling such problems that are more "Pythonic". Just like with spoken languages, programming languages have their charming idiosyncrasies. Normal programming languages tend to accomplish things multiple times by doing something like the following C code:
for (x=0;x<3;x++) { Lets_do_this_thing_thrice() }
    
That's nice and since *many* languages inherited this mentality and even exact syntax from C, many people feel this is how a loop should be approached. But in real programming, it is relatively infrequent that you know how big your loop is. Very often in this C style you must first survey your data to find out how much looping you want to do. Let's say you have a list of numbers that you want to add but you don't know how many numbers. The first thing you have to do is find out, then you can put that in your loop syntax as a variable. The entire process has a fancy computer science name which is "iteration". If there is a list of numbers and I want to do something to all of them such as add each to a sum variable, the effective operation is iteration. Python just makes iterating the primary way of handling loops that involve data.

Python's iteration syntax uses the word "for" but it works somewhat differently than C styled languages. The format is "for VAR in LIST:" followed by a block. Inside the block the variable, VAR, is set to each item of LIST, which of course is a list. If there are 10 items in LIST, the loop block will execute 10 times and each time VAR will be defined with the next item.

Here's an example showing the `for` loop as used by Python:
ListOf10= [1,2,3,4,5,6,7,8,9,10]
s=0      # This will be the sum variable.
for I in ListOf10:
    s+=I
print s
    
You might wonder, what if the list was a thousand? That's a lot of typing. The answer is an odd Pythonic built-in function called `range` that gets used less than you'd imagine if you're familiar with other programming languages. Remember, usually your data is already in a list and you have no idea how many items you have. If the situation is reversed and you don't have a list, but want one with a certain number of items, say 1001, here's how it's done:
ListOfThousand= range(1001)
for I in ListOfThousand:
    s+=I
    
Why did I use 1001? Let's look at the range() function more closely. To see exactly what it does, type it into the interpreter:
>>> range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
Ah, it starts with 0 so to get to 10 I need to specify 11 numbers. As you can see, the result is just a list of integers. This means that the `for` loop is always just going through a list. It's also helpful to know that it iterates in order of the list i.e. it doesn't randomly pick which list component to work on next.

If you were wondering why I used "s" and not "sum" to keep track of the sum variable, it turns out that Python has a built-in function called sum. Python isn't as puffed up with a lot of obscure keywords and functions as other languages (ahem Perl) but it has some. To add the integers 0 through 1000 this would suffice:
sum(range(1001))
    

The next example is more typical of iteration tasks. It takes a user's arbitrary string and looks for those dreaded "four letter words". It uses the `split()` function to take a string and break it up into a list of strings based on some separator. In this case the separator is a single space, ' '.

#!/usr/bin/python
usersays= raw_input('Say something: ')
list_of_words= usersays.split(' ')
for w in list_of_words:
    if len(w) == 4:    # len() is length function.
        print w
    

Say something: Pythons eat mice by opening their mouths to suck the rodents in.
mice
suck
    

The `for` command opens the door to iteration and computer science fans like iteration. It's quick and easy for everyone. This lesson just scratches the surface of Python's sophisticated iteration techniques, however in most cases, it should be enough to make your programs elegant and efficient.

--------------------------
Previous LWM Home Python Lessons Index Next
This page was created with only free, open-source, publicly licensed software.
This page was designed to be viewed with any browser on any system.
Chris X. Edwards ~ June 2008