"Learning Python with You Hand in Hand" 18-loop statement for

In the last article "Learning Python with You Hand in Hand" 17-Loop Termination , we learned two loop termination methods, break and continue, and at the same time, we optimized our game program by using the loop termination method.

Today, what we are going to learn is another loop statement-for loop. How important is the for loop? Let's put it this way, there may not be a program that does not need a for loop. Therefore, if you work hard and learn the for loop well, our skills will be able to reach a higher level.

Let's first understand the role of the for loop and several concepts.

The for loop is used to "traverse" a collection (string, list, tuple) or iterator.

The reason why "traversal" is enclosed in double quotes is because the word is so common that I think the word "traversal" is customized for the for loop. In terms of meaning, traversal can be understood as reading one by one. From an object point of view, the traversed object is a collection or iterator, and at the same time, only a collection or iterator can be "traversed".

The type of collection can be string, list or tuple. The string has been mentioned before, traversing the string is to read each character in the string one by one. Although we haven't talked about the list yet, we have already touched it before. It is a collection of several elements enclosed in square brackets like [1, 2, 3, 4, 5]. To traverse the list is to read each element in the list one by one. Tuple is also the concept we will talk about later. It is a collection of several elements enclosed in parentheses like (1, 2, 3, 4, 5) (you don't need to know the concept of tuples first). To traverse the tuple is to read each element in the tuple one by one.

The concept of iterators is a bit more complicated, so you can simply understand it. Iteration is a way to access the elements of a collection, and an iterator is an object that can remember where to traverse (Python is everything is an object). The iterator object is accessed from the first element of the collection until all the elements have been accessed. It can only go forward and not go back. Therefore, the process of traversal is iteration, and the object of traversal is iterator.

After understanding the concept, let's take a look at the structure of the for loop. The for loop is composed of for...else..., where the else part can also be omitted.

for 元素 in 集合:
    执行语句1
else:
    执行语句2

Unlike the while loop, the judgment condition of the while loop is changed to the iterative process of the for loop. The while loop determines the number of loops based on the judgment condition, and the for loop determines the number of loops based on the number of elements in the set.

The same as the while loop is the format requirements (colon and indentation), else can be omitted (for loops are commonly used to omit the structure of the else), and break and continue can also be used to terminate the loop, and the termination rules are the same (break terminates the entire Loop, continue to terminate the current loop).

The sentence structure of the for loop is translated into natural language and can be expressed as:

For each element in the collection, execute statement 1, and after traversing the collection, execute statement 2.

From the point of view of natural language, the process of for loop is easier to understand, but the difficult thing may be the concept of collection and traversal. Next, we will show you a few examples according to the different types of collections in the for loop, so that you can intuitively experience the traversal process and the traversal effects of different types of collections.

Strings are the type we know best so far, so we start with strings.

1. String

The string is composed of characters, so the elements of the string are these characters. When we traverse the string as a collection of for loops, we read each character of the string one by one from left to right.

When I just introduced the for loop structure, there was actually another key point that was not mentioned. This is in the iterative statement "for element in set" of the for loop, the "element" is not really an element in the set, but is written as "for element in set" in order to let everyone understand the traversal process Look like.

In fact, in the "for element in set", the position of the element is a variable name. In each iteration, the variable name is cyclically assigned to the value of each element in the set. When the set is a string, this variable will be assigned to every character in the string; when the set is a list or tuple, this variable will be assigned to every element in the list or tuple.

Let’s take a string as an example to take a look at the process of traversal, assignment, and loop together.

In [1]: str = "Hello World!"   # 集合是字符串,每一个字母、空格、标点符合都是一个字符,或者说是一个元素
        for letter in str:   # letter是一个变量名,可以起任何的变量名,只是为了程序好阅读,才根据元素的内容,起名叫做letter
            print(letter)   # 每一次循环,变量letter就会被赋值成一个字符(元素)的值,并执行print()
Out[1]: H
        e
        l
        l
        o
        
        W
        o
        r
        l
        d
        !

In the example above, the set is "Hello World!" (not including ""). The traversal process is to read the value of each character (element) in the set one by one, namely: H, e, l, l, o,, W, o, r, l, d, !. Then in each loop, assign these values ​​to the variable letter one by one, and finally execute print.

This example is relatively simple, but also very direct. You should be able to understand the process of traversal and assignment a little bit. It doesn't matter if you haven't understood it yet, we have many examples to help everyone understand.

The following is a slightly more difficult example. One is the addition of escape characters in the string. Let's see how to traverse. The second is the addition of two loop termination conditions, continue and break, and the third is the addition of else. , Let's see if it will work.

In [2]: str = "\\Hello World!\n"   # 转义字符不会被当做两个字符处理的,遍历时\\就是一个字符\,\n也就是一个回车符(打印出来是一行空行)
        for abc in str:   # 随机换了一个别的变量名,也是一样的,说明变量名和遍历的元素是没有关系的,不是因为变量名是letter,才按照字母遍历的
            print("该次遍历打印的字符是:{},".format(abc), end='')
            if abc == 'o' or abc == 'r':
                print("即将执行continue,不会打印下面那句话,循环继续。")
                continue
            if abc == 'd':
                print("即将执行break,不会打印下面那句话和else,循环终止。")
                break
            print("会打印这句话,循环继续。")
        else:   # else因为也是循环结构内的一部分,会被break终止,不会运行
            print("打印完成")
Out[2]: 该次遍历打印的字符是:\,会打印这句话,循环继续。
        该次遍历打印的字符是:H,会打印这句话,循环继续。
        该次遍历打印的字符是:e,会打印这句话,循环继续。
        该次遍历打印的字符是:l,会打印这句话,循环继续。
        该次遍历打印的字符是:l,会打印这句话,循环继续。
        该次遍历打印的字符是:o,即将执行continue,不会打印下面那句话,循环继续。
        该次遍历打印的字符是:,会打印这句话,循环继续。
        该次遍历打印的字符是:W,会打印这句话,循环继续。
        该次遍历打印的字符是:o,即将执行continue,不会打印下面那句话,循环继续。
        该次遍历打印的字符是:r,即将执行continue,不会打印下面那句话,循环继续。
        该次遍历打印的字符是:l,会打印这句话,循环继续。
        该次遍历打印的字符是:d,即将执行break,不会打印下面那句话和else,循环终止。

Although the above example is a bit complicated, it can actually be seen as two parts. One part is the traversal process of the loop, which is not much different from the first example, except that an escape character is added. The second part is the termination of the loop statement, which is similar to the example we gave in the previous article.

After understanding how a string is traversed as a collection, let's look at the list again.

2. List

Although we haven't learned the list, we have used it in some previous examples. A list is an ordered group of elements enclosed by square brackets. Now everyone can understand the list as a container. The elements separated by commas can be of many types such as numbers, strings, and variables.

As a simple example, let's see how a list is traversed as a collection. Because we have demonstrated the termination of the loop and the else instance before, in order to focus more on the traversal process later, we no longer write complicated instances.

In [3]: a = 'Python'
        lst = [1, 'a', 2, 'b', a, '3']   # 第5个元素a是个变量,第6个元素'3'是字符串不是数字
        for a in lst:   # 变量名虽然是可以随便起的,但建议在程序中,还是使用有意义的变量名
            print(a)
Out[3]: 1
        a
        2
        b
        Python
        3

In the above example, there are a total of 5 occurrences of "a", but each "a" has a different meaning or function.

The first'a' is a variable name, and its value is a string'Python', which is an assignment process;

The second'a' is a string;

The third'a' and the first'a' both refer to the same variable, here is the value of the reference variable a;

The fourth'a' is also a variable name, which is assigned to each element in the set. At this time, although the assignment result of the first'a' is invalid, it will not affect the value of the elements in the list, because after running the second line of the program, the value of lst has become [1,'a', 2, 'b','Python', '3'];

The fifth'a' and the fourth'a' refer to the same variable and also refer to the value of variable a.

3. Tuples

Tuples are also a data structure we will talk about later, so I don't want to involve too much here. Its form is an ordered group of elements enclosed in parentheses. Therefore, the content of the list as a set above is exactly the same for tuples, as long as the square brackets are turned into parentheses.

Speaking of this, the various types of collections are over, but there is another traversal method most commonly used in for loops that needs to be introduced. The reason why it is called "method" and not "type" is because the essence of this method is a list, but it uses a function that can easily generate a list as an expression. This function is range().

4. Range() function

Before, in order to illustrate the process of for loop traversal, the examples given were to display elements, and the types of elements were as diverse as possible to expand everyone's thinking. But in fact, when we apply a for loop, the most commonly used one is to traverse a sequence of numbers. For example, the following figure is implemented by traversing a sequence of numbers using a for loop.

In [4]: for num in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
            print(' ' * (9 - num), '* ' * num, ' ' * (9 - num), sep='')
Out[4]:         *         
               * *        
              * * *       
             * * * *      
            * * * * *     
           * * * * * *    
          * * * * * * *   
         * * * * * * * *  
        * * * * * * * * *

The number sequence here uses a list, but each element is still displayed. It’s okay when the number of elements is relatively small. If the number is large, or when the number change rule is more complicated, this is not very convenient. At this time, we need the range() function to come out.

The role of the range() function is to generate a list of integer numbers. Its basic grammatical expression is:

range(start_num, end_num, step)

Since Python uses the left-closed right-open rule, start_num is the starting number of the number sequence (write a few is a few); step is the step size, that is, the interval value between each number in the number sequence; end_num is the last number of the number sequence A number will not exceed or equal the value, but the final number needs to be calculated by star_num and step.

The default value of strat_num is 0, and the default value of step is 1. Therefore, when only range(end_num) is written, the number sequence from 0 to end_num-1 is generated by default. For example, range(10) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

When step is omitted and only range(strat_num, end_num) is written, the sequence of integers from strat_num to end_num-1 is generated. For example, range(-5, 10) is equivalent to [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

When all the parameters are set, it will start from start_num and generate a sequence according to the increment of step (negative increment if step is a negative number) until end_num, but the last number can neither be equal to end_num nor exceed end_num . For example, range(-5, 10, 3) is equivalent to [-5, -2, 1, 4, 7] (right open interval, cannot include 10).

When the step parameter is a positive number, start_num is less than end_num. The above is an example of this situation.

When the step parameter is negative, start_num is greater than end_num. For example, range(10, -5, -3) is equivalent to [10, 7, 4, 1, -2] (also cannot include -5).

 If step is positive, but start_num is less than end_num, or step is negative, but start_num is greater than end_num, although the program will not report an error, but the result of the traversal of the number sequence is empty, it will end the traversal and execute else (if any Words) or the statement after the for loop.

In [5]: for num in range(10, -5, 3):
            print(num)
        print("程序结束。")
Out[5]: 程序结束。

Therefore, the role of the range() function in the for loop is to make it more convenient for us to generate a list of integers as the traversed object. It is the same as the case where the list is traversed as a collection, and there is not much other conceptual content needed. Introduction.

Using the range() function, the previous program for printing graphics can be simplified to:

In [6]: for num in range(10):
            print(' ' * (9 - num), '* ' * num, ' ' * (9 - num), sep='')
Out[6]:         *         
               * *        
              * * *       
             * * * *      
            * * * * *     
           * * * * * *    
          * * * * * * *   
         * * * * * * * *  
        * * * * * * * * *

The above is the introduction to the for loop. At this point, we have all introduced Python's control flow statements if, while, for, and loop termination methods break and continue. If you can understand the content of these articles thoroughly, at least in terms of sentence control such as judgment, looping, and termination, there is no difference between you and the master in terms of knowledge reserve. The rest is how you can be flexible in the program Used.

In the next article, we will make a small summary of what we have learned before, and at the same time we will write a more complex game program, which not only applies to if, while, for loops and their nesting, but also includes the termination of the loop , Random functions, string functions and other knowledge points, hope to help you digest, understand and apply the previous content, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesu Python" public account, read other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

For Fans: Follow the "also said Python" public account, reply "hand 18", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/98851593