Basic tutorial for learning Python (learning Python)--4.2 Python's counting loop body for statement_PHP tutorial

WBOY
Release: 2016-07-20 11:15:27
Original
1162 people have browsed it

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 ​
  1. for variable in [value1, value2,....]:
  2. (TAB)statement
  3. (TAB)statement
  4. (TAB)etc.

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 ​
  1. def main():
  2. print('I will display the numbers 1 through 5.')
  3. for num in [1, 2, 3, 4, 5 ]:
  4. print(num)
  5. # Call the main function.
  6. main()
Code

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440189.htmlTechArticleAnother loop body structure of Python is the counting loop body for, which realizes the cyclic execution of certain statement blocks through the for loop A certain number of times, its usage grammatical structure is as follows. Python's for loop application...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template