Loops and Iterators
Loops and iterators both do the same basic thing—repeat a section of code until some condition is met. With a loop, the repetition can be any arbitrary code sequence, whereas an iterator steps through an iterable object.
An iterable object is an object that can be indexed (stepped through) in a sequential way. The most common iterable types in Python are the sequence types—strings, lists, tuples and ranges.
The While Loop
To create a program loop in Python, you use the while statement. For example, here is a very simple loop:
a = 1 while a < 5: print(a) a+=1
This should be easy to follow:
- Set the value of a to 1;
- Start a loop with the while statement;
- Print out the current value of a;
- Increment a; and
- Repeat while the expression “a < 5” is True.
If you run this code at the Python prompt, your output should look like this:
Python’s while loops are very useful and can be used for much more than simple tasks like printing out a variable. For example, the factorial (!) of any number is simply the multiplication of the number with all the preceding integers (so 4! is equal to 123*4).
Here’s how to calculate the factorial of 9 with a while loop:
In the first line I am using multiple assignment, which is a useful feature of Python’s programming syntax. The statement fact, mul = 1, 2 is a shorthand way of writing:
fact = 1 mul = 2
Line 3 is where all the magic happens. First, we multiply the current value of
mul and then we increment
mul by 1. We then print out the new value of
Breaking out of Loops
The break and continue statements allow you to exit a loop before the loop condition is met. Consider the following code:
a, b = 1, 1 while a < 5: print("a =", a) a +=1 while b < 5: print("b =", b) if b == 2: b = 1 break b +=1
break statement will only exit the currently running loop, so in the above example the break statement only exits the inner while loop. Let’s see what the output is when we run this code:
You can see that the break statement doesn’t affect the outer loop—it continues to run until “a < 5” is False. Because the inner loop always breaks when b is equal to 2, the inner while loop never completes.
continue statement, on the other hand, won’t execute any of the code after the continue, but instead it jumps to the next iteration of the loop. Consider the following code:
a = 0 while a < 5: a+=1 if a == 3: print("My favorite number is", a) continue # Go to next iteration of loop print("a =", a) # The continue statement will stop # this from printing when a equals 3
Run this code and you should see a different string printed when a equals 3:
continue statements can also be used inside a for loop.
Iterating with a For Loop
The for loop is designed to step through an iterable item. It takes the basic form:
for [item] in [iterable]:
As I said earlier in the chapter, the most common iterables are strings, lists, tuples and ranges. Here are some examples:
>>> word = "Hello" >>> for char in word: # Step through each character ... print(char) # in the word ... H e l l o >>> lst = ["1","2","3"] # Step through each item >>> for item in lst: # in the list ... print(item) ... 1 2 3 >>> tup = (1,"two", 3) # Step through each item >>> for item in tup: # in the tuple ... print(item) ... 1 two 3 >>> for i in range(5): # The range function provides you ... print(i) # with a sequence of integers ... 0 1 2 3 4 >>>
This should be easy to follow. The
range() function we haven’t covered, but it’s basically an easy way of creating a sequence of numbers. More on the
range() function in the Python documentation.