Home > Article > Backend Development > Basic tutorial for learning Python (learning Python)--4.2 Python's counting loop body for statement_PHP tutorial
Another loop structure in Python is the counting loop for. Through the for loop , certain statement blocks can be executed for a certain number of times. The syntax structure is as follows .
Python's for loop application has the same idea as other high-level languages such as C, when the condition of for is met When, the statement block under for is executed. The difference is that the way of writing the condition of for is somewhat different from other high-level languages.
[python] view plaincopy
Here appears for the first time the left square bracket '[' and the right square bracket ']'. The data sequence enclosed by the left and right square brackets is called It is a list. We will explain the knowledge about list in detail later.
One thing to note here is that [value1,value2,...] must be followed by a colon:, Otherwise there will be syntax errors.
The loop of for works like this: Each time, a value valuex is taken out from the list behind in and is assigned a value There is a variable behind for, so how many times should it be looped? Loop as many times as there are data in the list. When all the data in the list has been fetched, the for will end. Therefore, the number of times for execution depends on the number of data in the list, as follows Let me give an example to illustrate.
[python]
view plaincopy Line 3 is a for loop that takes out one item from the list [1,2,3,4,5] each time The value is assigned to num, in the following list ([1, 2, 3, 4, 5]) There are 5 data in total. It can be seen that for can end after looping 5 times.
The running results are as follows
Let’s conclude by analyzing why the result is like this?
Each time the for loop extracts a data from [1, 2, 3, 4, 5] to num.