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
For element in sequence:
Statement
For example, we edit a file called fordemo.py.
For a 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
For a in range (10):
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 < 10:
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
For I in range (10):
if i = = 2:
Continue
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).
For I in range (10):
if i = = 2:
Break
Print I
When the loop executes to I = 2, the If condition is set, the break is triggered, and the entire loop stops.
Summarize
Range ()
For element in sequence:
While condition:
Continue
Break
-for cycle of Python learning notes