Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!
Loops are used to repeatedly execute some blocks of the program. From the previous selection structure, we have seen how to use indentation to represent the membership of a program block. The loop will also use a similar notation.
For Loop
The For loop requires a pre-set number of cycles (n), and then executes the statement that is subordinate to the for (n) times.
The basic structure is
In sequence: statement
For example, we edit a file called fordemo.py.
In [3,4.4, ' life ']: print a
This loop takes one element at a time from the table [3,4.4, ' life '] (recall: The table is a sequence), assigns the element to a, and then executes the action (print) that belongs to the for.
Introduces a new Python function , range (), to help you create a table.
IDX = range (5)print idx
You can see that the IDX is [0,1,2,3,4]
The function is to create a new table. The elements of this table are integers, starting with 0, the next element is 1 larger than the previous one, until the upper bound is written in the function (excluding the upper bound itself)
(About range (), there is a lot of usage, interested can be consulted, Python 3, range () usage changes, see comment area)
Example
In range: print a**2
While loop
The use of the while IS
While condition: statement
The while loop executes the statement that is subordinate to it until the condition is False (false)
Example
While I <: print i i = i + 1
Interrupt loop
Continue # in an execution of a loop, if you encounter continue, skip this execution and proceed to the next operation
Break # Stops execution of the entire loop
In range: if i = = 2: print i
When the loop executes to I = 2, the If condition is set, the continue is triggered, the execution is skipped (no print is executed), and the next execution is continued (i = 3).
In range: if i = = 2print i
When the loop executes to i = 2, the If condition is set, the break is triggered, and the entire loop stops.
Summary
Range ()
For element in sequence:
While condition:
Continue
Break
Python base 06 Loop