18. Python's for loop statement

While loop statements are generally used for infinite loops or some conditional judgments, while our for loops are generally used for traversing a sequence or traversing some data.
This sequence can be a list or a Str, because Str is also a sequence of multiple characters.

Insert picture description here
The variable in the above figure, every time it enters the for loop, that is to say, each loop of the for will take a value in the sequence, and access the value in the sequence through this variable.
The special feature of the for loop statement in Python is that it also provides an else statement, that is, when the last for loop variable is not in the sequence sequence, that is to say, when we traverse to the end, we will enter the end of the else In the code.

In the C language, we often use a number to traverse in the for loop, because sometimes it is used to access a subscript or do some numerical calculations. At this time, we can use another form of our for:

for i in range(10):

The value of i will be from 0 to 9, because range is to temporarily generate a sequence. We pass a 10 to range, which is 0 to 9. Anyway, it is not greater than 10 and starts from 0.

Of course, when we want to specify the value range of this sequence , the Python language also provides a method:

for i in range(5, 10, 2):

The range is from 5 to 9, excluding 10, and the third parameter indicates the step size, that is, how much to increase each time from 5 to 10 (that is, 5, 7, 9 increase in this way).
Insert picture description here
Note that in the last execution, after entering print(i, end = ""), it will enter the else statement and execute print("\t end = ", i), which is different from the else of the while loop.

If you only want to do this traversal of numbers, you can generate a sequence through range:
Insert picture description here

Guess you like

Origin blog.csdn.net/zhaopeng01zp/article/details/109275812