Loop is used to repeatedly execute some program blocks. From the selection structure described above, we have seen how to use indentation to represent the membership relationship of the program block. Loop will also use a similar method. For loop is used to repeatedly execute some program blocks. From the selection structure described above, we have seen how to use indentation to represent the membership relationship of the program block. Loop will also use a similar method.
For loop
For loop, you need to set the number of cycles (n) in advance, and then execute the for statement n times.
The basic structure is
For element in sequence:
Statement
For example, we edit a file named forDemo. py.
for a in [3,4.4,'life']: print a
This loop is to retrieve an element from the table [3, 4.4, 'Life'] each time (recall: The table is a sequence), and assign this element to, then execute the for Operation (print ).
Introduce a new Python function range () to help you create a table.
idx = range(5)print idx
We can see that idx is [0, 1, 2, 3, 4].
This function is used to create a new table. The elements in this table are all integers. starting from 0, the next element is 1 larger than the previous one until the upper limit written in the function (excluding the upper limit itself)
(For more information about range (), see range () in Python 3. for details, see the comment area)
Example
for a in range(10): print a**2
While loop
While is used
While condition:
Statement
While will continuously execute the statements that belong to it until the condition is False)
Example
while i < 10: print i i = i + 1
Interrupt loop
Continue # if a continue is encountered during a loop execution, skip this execution and perform the next operation.
Break # stop the entire execution cycle
for i in range(10): if i == 2: continue print i
When the loop is executed to I = 2, the if condition is true, and the continue is triggered. skip this execution (do not execute print) and continue the next execution (I = 3 ).
for i in range(10): if i == 2: break print i
When the loop is executed to I = 2, the if condition is true, the break is triggered, and the entire loop is stopped.
Summary
Range ()
For element in sequence:
While condition:
Continue
Break
The above is a detailed introduction to the basic Python loop. For more information, see other related articles in the first PHP community!