Web site translator - CHAPTER 5 CONDITIONALS, LOOPS, AND SOME OTHER

CHAPTER 5 CONDITIONALS, LOOPS, AND SOME OTHER STATEMENTS 95 for Loops The while statement is very flexible. It can be used to repeat a block of code while any condition is true. While this may be very nice in general, sometimes you may want something tailored to your specific needs. One such need is to perform a block of code for each element of a set (or, actually, sequence or other iterable object) of values. You can do this with the forstatement: words = [’this’, ‘is’, ‘an’, ‘ex’, ‘parrot’] for word in words: print word or numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: print number Because iterating (another word for looping ) over a range of numbers is a common thing to do, there is a built-in function to make ranges for you: >>> range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Ranges work like slices. They include the first limit (in this case 0), but not the last (in this case 10). Quite often, you want the ranges to start at 0, and this is actually assumed if you only supply one limit (which will then be the last): >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Tip There is also another function called xrange that works just like range in loops, but where range creates the whole sequence at once, xrange creates only one number at a time. This can be useful when iterating over huge sequences more efficiently, but in general you needn t worry about it. The following program writes out the numbers from 1 to 100: for number in range(1,101): print number Notice that this is much more compact than the while loop I used earlier. Tip If you can use a for loop rather than a while loop, you should probably do so.
You want to have a cheap webhost for your apache application, then check apache web hosting services.

Comments are closed.