Programming A for loop using Python

Source: Internet
Author: User
Tags python list
This article describes the python for loop. The for loop is used to iterate projects in the python set, including the python tuple, string, and list container types discussed in the previous article "explore Python. By using the range (or xrange) method, the for loop can also be used to access elements of a container type. In addition, you can use the range method to execute a specific number of statements in a for loop.

For Loop

The article "explore python, Part 1: program with Python" in the previous sections of this series discusses if statements and while loops, composite statements, and the appropriate indentation of Python statements to indicate the relevant Python code blocks. The end of this article introduces the python for loop. However, in terms of its usage and functions, the for loop is worth noting. Therefore, this article separately describes this loop.

A For loop has a simple syntax that allows you to extract a single project from a container object and perform some operations on it. To put it simply, you can use a for loop to iterate the items in the object set. The object set can be any Python container type, including the tuple, string, and list types discussed in the previous article. However, container metaphor is more powerful than the three types. Metaphor includes other sequence types, such as dictionary and set. They will be discussed in future articles.

But please wait! More information: The for loop can be used to iterate any object that supports iteration of metaphor, which makes the for loop very useful.

Listing 1 shows the basic syntax of the For Loop and shows how to use the continue and break statements in the for loop.

Listing 1. pseudo code of 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, "explore python, Part 1: Explore Python-type hierarchies", introduces Python tuple. As described in this article, the tuple type is an unchangeable heterogeneous container. This mainly means that tuple can store different types of objects, but once it is created, it cannot be changed. Listing 2 demonstrates how to use the for loop to iterate the tuple element.

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

In this example, a tuple named T is created to store integers 0 to 9 (including 9 ). The first for loop iterates this tuple and accumulates the sum of values in the tuple in the count variable. Once the Code has iterated all the elements in the tuple, it will enter the else clause of the For Loop and print the value of the count variable.

The second for loop shown in Listing 2 also iterates all elements in the tuple. However, it only accumulates the values of the items that can be divisible by 2 in the container (remember that if the expression is non-zero, the IF statement is true, when num cannot be divisible by 2, The % operator returns a non-zero value ). This restriction is achieved by using the appropriate if statement and continue statement. As described in the previous article, the continue statement starts the next iteration of the loop containing it. Another way to achieve the same result is to test whether the current item in tuple is an even number (if not num % 2 :). If it is true, add the current item to the total running number. Once the code completes the iteration in tuple, The else clause is called to print the sum.

The third article in this series, "exploring Python: Part 1: Exploring Python-type hierarchies", discusses Python string. String is an unchangeable homogeneous container, which means it can only store characters and cannot be modified once it is created. Listing 3 demonstrates 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, all of which iterate on the same string. The first for loop iteration string "python is a great programming language !" Print a character in the string at a time. In this example, a comma is added after the print statement variable C. This enables the print statement to print character values followed by space characters, rather than line breaks. If no comma is followed, all characters are printed in separate rows, which is hard to read.

The next two for loops iterate over the string and calculate the number of vowels ("A", "E", "I", "O", or "u") it contains "). The second for loop searches for only lower-case vowels when iterating the original string. The third for loop iteration calls the temporary string returned by the lower method of the string object. The lower method converts all characters in string to lowercase. Therefore, the third for loop can find the other two vowels.

The fourth article in this series, "explore python, Part 1: Explore Python hierarchies", introduces Python list. List is a heterogeneous variable container, which means it can store different types of objects and be modified after creation. Listing 4 demonstrates 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, "  ", 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 flexible Python container type (you will see it multiple times in other articles in this series), this example may seem too simple. However, this is part of the main point: using a for loop makes it very easy to process every project in the container, even to process a list containing various objects. In this example, all the items in the python list are iterated, and each item and its corresponding Python type are printed in a separate row.

Iteration and variable container

Python list is a variable sequence that provides a curious possibility: The for loop subject can modify its list that is being iterated. As you may think, this is not good. If you perform this operation, the python interpreter will not work well, as shown in listing 5.

Listing 5. Modify the 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, 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]

In this example, if an odd number is found in the original list, the first for loop inserts a value of 100 at the beginning of the list. Of course, this is an unusual way to demonstrate this problem, but it is very good. Once the three-point Python prompt is followed by the Enter key, the python interpreter is in the chaos of infinite loops. To stop this confusion, you must press Ctrl-C (which is displayed as ^ C in the python output) to interrupt the process, and then a keyboardinterrupt exception occurs. 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. Now the for loop iterates the copy and modifies the original list. The final result is the modified original list, which starts with five new elements with a value of 100.

For Loop and sequential Index

If you have used other programming languages, the python for loop may look a bit odd. You may think it is more like a foreach loop. The C-based programming language has a for loop, but it is designed to execute a specific number of operations. Python for loops can be simulated by using the built-in range and xrange methods. The two methods are demonstrated 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 containing a series of integers. Generally, a single value is provided to call the range method, which is used as the upper limit of the integer list. Zero is the starting value. Therefore, calling range (10) will create a list containing integers 0 to 9 (including 9. The range method accepts the start index and step size. Therefore, calling range () will create an integer list from 11 to 19 (including 19), while 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 necessary. For example, when listing 6 tries to print the newly created xrange, no data is displayed except the xrange name. When a large number of integers need to be iterated, The xrange method is more suitable because it does not create a large list, which consumes a lot of computer memory.

Listing 7 demonstrates how to use the range method in a for loop to create a multiplication table ranging from 1 to 10 (including 10.

Listing 7. Creating 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

In this example, two for loops are used. The for loop outside focuses on each row in the multiplication table, and the nested for loop focuses on the columns in each row. Each loop iterates the list containing integers 1 to 10 (including 10. The print statement uses a new concept named string formatting to create a table with exquisite format settings. String formatting is a very useful technique. It is used to create a string composed of different data types in a beautifully formatted layout. The current details are not important, and will be described in future articles (anyone familiar with the printf method of c programming language will be familiar with this content ). In this example, string formatting specifies that a new string will be created from the integer and three characters must be retained to store the integer (if the integer is less than three characters, it will be filled with spaces on the left, so that the data is arranged neatly ). The second print statement is used to print a new row, so that the next row in the multiplication table is printed in the new row.

The range method can also be used for iteration containers to access each item in a sequence by using an appropriate index. To perform this operation, you need to include an integer list of permitted range index values of the container, which can be easily implemented by using the range method and Len method, as shown in listing 8.

Listing 8. indexing containers in 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 11
Language! 9

The final example demonstrates how to use the Len method as the parameter of the range method and create an integer list that can be used to separately access each character in the string. The second for loop also shows how to split a string into a list of substrings (using space characters to indicate the boundary of the substrings ). For loop iteration sub-string list, print each sub-string and its length.

Conclusion

This article discusses the python for loop and demonstrates some of its usage methods. You can use a for loop with any Python object that provides the iterator. These objects include built-in sequence types such as tuple, string, and list. When a for loop is used with a list sequence, you can use them in many cases. Python provides a simple mechanism for combining these two concepts, called list comprehension, which will be described in future articles.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.