For loop
Earlier in this series, "Explore Python, part 5th: Programming in Python" discusses the IF statement and the while loop, discusses compound statements, and appropriately indents Python statements to indicate the associated Python code block. The end of this article describes the Python for loop. But for the use and functionality of the For loop is more interesting, so this article describes the cycle alone.
The For loop has a simple syntax that allows you to extract and manipulate a single item from a container object. Simply put, you can use a for loop to iterate through the items in the collection of objects in. The collection of objects can be any Python container type, including the tuple, string, and list types discussed in previous articles. But container metaphor are more powerful than these three types. Metaphor includes other sequence types, such as dictionary and set, which will be discussed in future articles.
But wait a moment, please! More information: A For loop can be used to iterate over any object that supports iterative metaphor, which makes a for loop useful.
The basic syntax for the For loop is shown in Listing 1 and shows how to use the Continue and break statements in the For loop.
Listing 1. Pseudo code for Loop
For item in container:
if Conditiona: # Skip This item
continue
elif conditionb: # do with loop
break
# Action to repeat for each item in the container
else:
# action to take once we have finished the loo P.
The second article in this series, "Exploring Python, Part 2nd: Exploring the hierarchy of Python types" introduces the Python tuple. As described in the article, the tuple type is an immutable heterogeneous container. This basically means that tuple can hold different types of objects, but once it is created, it cannot be changed. Listing 2 shows how to use the For loop to iterate over the tuple element.
Listing 2. For loops and tuple
>>> T = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> count = 0
>>> for num in t: ... Count + = num
... else: ... Print Count
...
>>> count = 0
>>> for num in t: ... If num% 2: ... Continue ... Count + = num
... else: ... Print Count
...
20
This example first creates a tuple named T that holds integers 0 through 9 (including 9). The first for loop iterates this tuple and accumulates the sum of the values in the tuple in the count variable. Once the code has iterated over all elements in tuple, it enters the ELSE clause for the FOR loop, printing the value of the count variable.
The second for loop shown in Listing 2 also iterates through all the elements in the tuple. However, it only accumulates the values of those items in the container that are divisible by 2 (remember that if the expression is Non-zero, the IF statement is true, and num cannot be divisible by 2, the% operator returns a non-0 value). This restriction is accomplished by using the appropriate if statement and the continue statement. As described in the previous article, the continue statement causes the loop that contains it to begin the next iteration. Another way to achieve the same result is to test whether the current item in the tuple is an even number (using if not num% 2:), and if true, add the current item to the running sum. Once the code completes the iteration in tuple, the ELSE clause is invoked and the sum is printed.
The third article in this series "Exploring Python: Part 3rd: Exploring the hierarchy of Python types" discusses Python string. A string is an immutable homogeneous container, which means that it only holds characters and cannot be modified once it is established. Listing 3 shows how to use Python string as a container for the For loop.
Listing 3. For loop and string
>>> st = "Python is A great programming language!"
>>> for C in St:
... Print C,
...
P y t h o n i s a g R e a T P r o g r a m m i n g L a n g u a g E!
>>> count = 0
>>> for C in St:
... If C in "Aeiou":
... Count = 1
... else: ... Print Count
...
>>> count = 0
>>> for C in St.lower ():
... If C in "Aeiou":
... Count = 1
... else: ... Print Count
...
12
This example provides three different for loops, all of which iterate over the same string. The first for loop iteration string "Python is a great programming language!" and prints one character in the string at a time. In this example, a comma is added to the PRINT statement variable C. This lets the print statement print a character value followed by a space character instead of a newline character. If there is no subsequent comma, the characters will all print in a separate line and will be difficult to read.
The next two for loop iterates the string and calculates how many vowel letters it contains ("a", "E", "I", "O", or "U"). The second for loop finds only lowercase vowels when iterating the original string. The third for loop iteration returns a temporary string by calling the lower method of the string object. The lower method converts all characters in a string to lowercase. Therefore, a third for loop can find another two vowel letters.
The fourth article in this series, "Exploring Python, Part 4: Exploring the Python type hierarchy" introduces the Python list. A list is a heterogeneous variable container, which means that it can hold different types of objects and can be modified after creation. Listing 4 shows how to use the list and for loops.
Listing 4. For Loop and list
>>> mylist = [1, 1.0, 1.0j, ' 1 ', (1,), [1]]
>>> for item in MyList:
... Print item, "\ t", type (item)
...
1 <type ' int ' >
1.0 <type ' float ' >
1j <type ' Complex ' >
1 <type ' str ' >
(1,) <type ' tuple ' >
[1] <type ' list ' >
Since the list is a flexible Python container type (you'll see it many times in the rest of this series), this example may seem too simplistic. However, this is a part of the point: Using a For loop makes each item in the processing container very simple, even with a list of different objects. This example iterates through all the items in the Python list and prints each item and its corresponding Python type in a separate row.
Iterations and Variable containers
The Python list is a mutable sequence that provides an intriguing possibility that the for loop body can modify the list that it is iterating over. As you might think, this is not good, and if you do this, the Python interpreter will not work well, as shown in Listing 5.
Listing 5. To modify a container in the For loop
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for item in MyList:
... If Item% 2: ... Mylist.insert (0)
...
^ctraceback (most recent):
File "<stdin>", line 3, in?
Keyboardinterrupt
>>> Print mylist
[MB, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Many lines del eted for clarity
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for item in mylist[:]:
. .. If Item% 2: ... Mylist.insert (0)
...
>>> print MyList
[100, 100, 100, 100, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The first for loop in this example, as long as the odd number is found in the original list, inserts a value of 100 at the beginning of the list. Of course, this is an unusual way to demonstrate the problem, but it's very good. Once you press Enter after the three-point Python prompt, the Python interpreter is in the midst of an infinite loop of chaos. To stop this confusion, you must break the process by pressing CTRL-C (which appears as ^c in the Python output), and then a Keyboardinterrupt exception will occur. If you print out the modified list, you will see that MyList now contains a large number of elements with a value of 100 (the exact number of new elements depends on the speed at which you interrupt the loop).
The second for loop in this example demonstrates how to avoid this problem. Use the slice operator to create a copy of the original list. The For loop now iterates over the copy and modifies the original list. The final result is the modified original list, which now starts with a new element with five values of 100.
For loop and sequence index
If you have used other programming languages, the Python for loop might look a little odd. You might think it's more like a foreach loop. The C-based programming language has a for loop, but it is designed to perform a specific number of actions on a series of operations. The Python for loop can simulate the behavior by using the built-in range and Xrange methods. The two methods are shown in Listing 6.
Listing 6. Range and Xrange methods
>>> r = Range (Ten)
>>> print R
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> type (r)
<ty PE ' list ' >
>>> xr = xrange (ten)
>>> print XR
xrange (a)
>>> type (XR)
<type ' xrange ' >
This example first demonstrates the Range method, which creates a new list that contains a series of integers. The general form of calling the Range method is to provide a single value that is used as the upper bound of the integer list. Zero is the starting value. Therefore, call range (10) creates a list containing integers 0 through 9 (including 9). The Range method accepts the starting index and the step size. Therefore, call Range (11,20) creates an integer list from 11 through 19 (containing 19), and call range (12, 89, 2) creates an even list from 12 to 88.
Because the Xrange method also creates an integer list that uses the same parameters, it is very similar to the Range method. However, the Xrange method creates integers in the list only when needed. For example, in Listing 6, when you try to print out a newly created xrange, no data is displayed except for the xrange name. When you need to iterate a large number of integers, the Xrange method is more applicable because it does not create a great list, which consumes a lot of computer memory.
Listing 7 shows how to use the range method within a for loop to create a multiplication table with integers 1 through 10 (including 10).
Listing 7. Create a multiplication table
>>> for row in range (1, one):
... For Col in range (1, one):
... Print "%3d"% (row * col),
... Print
...
1 2 3 4 5 6 7 8 9 ten 2 4 6 8 Ten 12
3 6 9 ( 30 km)
4 8 (5) # 20 6 ' (in)) 7 (
8 km) (MB) 9 ( 45) (MB) 80 km/I-yi 90 100
This example uses two for loops, and the outside for loop concerns each row in the multiplication table, and nested for loops focus on the columns in each row. Each loop iterates through the list containing integers 1 through 10 (containing 10). The innermost print statement uses a new concept called string formatting to create a beautifully formatted table. String formatting is a useful technique for creating a string that consists of different data types in a beautifully formatted layout. Details are not important now and will be covered in future articles (anyone who understands the printf method of the C programming language will be familiar with it). In this case, string formatting specifies that a new string will be created from an integer and that three characters need to be retained to hold the integer (if the integer is less than three characters, the left space will be filled with spaces so that the data is neatly arranged). The second print statement is used to print a new row so that the next row in the multiplication table is printed in a new row.
The Range method can also be used in an iterative container to access each item in the sequence by using the appropriate index. To do this, you need an integer list containing the allowable range index values for the container, which can be easily implemented by using the Range method and the Len method, as shown in Listing 8.
Listing 8. Index containers within a for loop
>>> st = "Python is A great programming language!"
>>> for index in range (len (ST)):
... Print St[index],
...
P y t h o n i s a g R e a T P r o g r a m m i n g L a n g u a g E!
>>> for item in St.split ('):
... Print item, len (item) ...
Python 6 is
2
A 1
great 5
programming
language! 9
This final example shows how to use the Len method as a parameter of the Range method to create an integer list that can be used to access each character in a string individually. The second for Loop also shows how to split a string into a list of substrings (using a space character to indicate the bounds of a substring). The For loop iterates through the substring list, printing each substring and its length.
Conclusion
This article discusses the Python for loop and demonstrates some of its ways of using it. You can use a for loop in conjunction with any Python object that provides an iterator, which includes built-in sequence types such as tuple, string, and list. The For loop and list sequence work together with powerful features, and you'll find yourself using them in many situations. Python provides a simple mechanism for combining these two concepts, called List Understanding, which will be covered in future articles.