The Personal Web Pages of Chris X. EdwardsXED's Python Lessons for Beginners |
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() } |
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 |
ListOfThousand= range(1001) for I in ListOfThousand: s+=I |
>>> range(11) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
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 |