This article mainly describes the use of the For loop in Python, from the IBM Official website Technical documentation, the needs of friends can refer to the following
For loop
Earlier in this series, "Explore Python, part 5th: Programming with Python" discusses the IF statement and the while loop, discusses compound statements, and appropriately indents Python statements to indicate the relevant Python code block. The Python for loop is described at the end of this article. For its use and functionality, however, the for loop is more of a concern, so this article tells the loop separately.
The For loop has a simple syntax that allows you to extract a single item from a container object and perform some action on it. Simply put, using a for loop, you can iterate over the items in a collection of objects. The object collection can be any Python container type, including the tuple, string, and list types discussed in the previous article. However, the functionality of the container metaphor is more powerful than these three types. Metaphor includes other sequence types, such as dictionary and set, which will be discussed in future articles.
But please wait a moment! More information: The For loop can be used to iterate over any object that supports iterative metaphor, which makes the For loop useful.
Listing 1 shows the basic syntax for the For loop, and also shows how to use the Continue and break statements in a for loop.
Listing 1. Pseudo-code for the For loop
for item in container:
if conditionA: # Skip this item
continue
elif conditionB: # Done with loop
break
# action to repeat for each item in the container
else:
# action to take once we have finished the loop.
The second article in this series, "Exploring Python, Part 2nd: Exploring the hierarchy of Python types," describes the python tuple. As described in the article, the tuple type is immutable heterogeneous container. This basically means that a tuple can hold different types of objects, but once it is created, it cannot be changed. Listing 2 shows how to iterate over the elements of a tuple using a for loop.
Listing 2. For Loop and tuple
>>> t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> count = 0
>>> for num in t:
... count += num
... else:
... print count
...
45
>>> count = 0
>>> for num in t:
... if num % 2:
... continue
... count += num
... else:
... print count
...
20
This example first creates a tuple named T, which holds integers 0 through 9 (inclusive of 9). The first for loop iterates over this tuple, accumulating the sum of the values in the tuple in the count variable. Once the code has iterated all the elements in the tuple, it enters the else clause of the FOR loop, printing the value of the count variable.
The second for loop shown in Listing 2 also iterates over all 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 nonzero, the IF statement is determined to be true and num cannot be divisible by 2 when using the% operator to return 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 a 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 the tuple, the ELSE clause is called, and the sum is printed.
The third article in this series, "Explore Python: Part 3rd: Exploring the hierarchy of Python types," discusses Python string. A string is an immutable homogeneous container, which means that it can hold only characters and cannot be modified once established. Listing 3 shows how to use a Python string as a container for a 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
...
10
>>> count = 0
>>> for c in st.lower():
... if c in "aeiou":
... count += 1
... else:
... print count
...
12
This example provides three different for loops, each of which iterates over the same string. The first for loop iterates over the string "Python is a great programming language!" and prints one character in a string at a time. In this example, the PRINT statement variable C is added with a comma. This causes the print statement to be followed by a space character instead of a newline character when the character value is printed. If there are no trailing commas, the characters will all be printed in a separate line and will be difficult to read.
The next two for loop iterates over the string and calculates how many vowels it contains ("a", "E", "I", "O", or "U"). The second for loop finds only lowercase vowels when iterating over 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, the third for loop can find an additional two vowel letters.
The fourth article in this series, "Explore Python, Part 4: Explore the hierarchy of Python types," describes the Python list. List is a heterogeneous mutable container, which means it can hold different types of objects and can be modified after they are created. Listing 4 shows how to use the list and for loops.
Listing 4. For loops 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 list is a very flexible Python container type (you'll see it many times in the rest of the series), this example may seem too simple. However, this is part of the point: Using a For loop makes it easy to work with each item in the container, even for lists that contain a variety 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 a curious possibility that the for loop body can modify the list that it is iterating over. As you might think, this is not good enough, and if you do this, the Python interpreter will not work well, as shown in Listing 5.
Listing 5. Modifying a container in a for loop
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for item in mylist:
... if item % 2:
... mylist.insert(0, 100)
...
^CTraceback (most recent call last):
File "<stdin>", line 3, in ?
KeyboardInterrupt
>>> print mylist
[100, ...., 100, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Many lines deleted for clarity
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for item in mylist[:]:
... if item % 2:
... mylist.insert(0, 100)
...
>>> print mylist
[100, 100, 100, 100, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The first for loop in this example, whenever an 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 hint, the Python interpreter is in an infinite loop of confusion. 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 occurs. If you print a 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 may look a bit 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 times for a series of operations. The Python for loop can simulate this behavior by using the built-in range and Xrange methods. Both of these methods are shown in Listing 6.
Listing 6. Range and Xrange methods
>>> r = range(10)
>>> print r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> type(r)
<type 'list'>
>>> xr = xrange(10)
>>> print xr
xrange(10)
>>> 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 as the upper bound of the integer list. Zero is the starting value. Therefore, calling range (10) Creates a list that contains integers 0 through 9 (including 9). The Range method accepts the starting index and the stride size. Therefore, calling range (11,20) creates an integer list from 11 to 19 (containing 19), and calling range (12, 89, 2) creates an even list from 12 to 88.
Because the Xrange method also creates an integer list (which uses the same parameters), it is very similar to the Range method. However, the Xrange method creates an integer in the list only when it is needed. For example, in Listing 6, when you try to print out the newly created xrange, no data is displayed except for the xrange name. The Xrange method is more appropriate when you need to iterate over a large number of integers because it does not create a large list, which consumes a lot of computer memory.
Listing 7 demonstrates how to use the range method within a for loop to create a multiplication table of integers 1 through 10 (inclusive of 10).
Listing 7. Create a multiplication table
>>> for row in range(1, 11):
... for col in range(1, 11):
... print "%3d " % (row * col),
... print
...
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
This example uses two for loops, and the outside for loop focuses on each row in the multiplication table, and the nested for loop focuses on the columns within each row. Each loop iterates over a list that contains integers 1 through 10 (containing 10). The innermost print statement uses a new concept called string formatting to create beautifully formatted tables. String formatting is a useful technique for creating a string that consists of different data types in beautifully formatted layouts. Now the details are not important and will be covered in future articles (anyone who understands the printf method of the C programming language will be familiar with them). In this case, the string formatting specifies that a new string will be created from an integer and that three characters are required to hold the integer (if the integer is less than three characters, it will be padded on the left with a space, thus arranging the data neatly). The second print statement prints a new line so that the next line in the multiplication table is printed on the new row.
The Range method can also be used to iterate through containers, accessing each item in the sequence by using the appropriate index. To do this, you need an integer list that contains 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 container within 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 11
Language! 9
This last example shows how to use the Len method as a parameter to 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 the substring). For loop iteration substring list, prints each substring and its length.
Conclusion
This article discusses the Python for loop and demonstrates some of its ways to use it. You can use a for loop in conjunction with any Python object that provides iterators, including built-in sequence types such as tuple, string, and list. The For loop and list sequence are powerful when used together, 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.