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
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)
Example
For a 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
For I in range (10):
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: 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
Python--for Loop