Loop introduction to basic python tutorials
- 2020-04-02 13:59:29
- OfStack
Loops are used to execute blocks repeatedly. From the selection structure in the last lecture, we have seen how to indent a block's membership. We'll use a similar notation for loops.
The for loop
The for loop needs to pre-set the number of loops (n), and then execute the statement that belongs to for n times.
The basic structure is
for The element in The sequence :
statement
For example, let's edit a file called fordemo.py
for a in [3,4.4,'life']:
print a
This loop is to take one element at a time from the table [3,4.4,'life'] (remember: a table is a sequence), assign that element to a, and then perform an operation under for (print).
Introduces a new Python function range() to help you set up tables.
idx = range(5)
print idx
You can see that idx is [0,1,2,3,4]
This function creates a new table. The elements of this table are all integers, starting at 0, and the next element is 1 larger than the previous one, all the way to the upper bound (not including the upper bound itself) written in the function.
(there's a lot more about range(), if you're interested, there's a change in range() in Python 3.)
For example,
for a in range(10):
print a**2
The while loop
The use of while is
while conditions :
statement
While is going to loop through it until it's False
For example,
while i < 10:
print i
i = i + 1
Interrupt cycle
continue # During one execution of the loop, if encountered continue, Then skip this execution and proceed to the next
break # Stop executing the entire loop
for i in range(10):
if i == 2:
continue
print i
When the loop executes to I = 2, if the condition holds, trigger continue, skip this execution (do not execute print), and proceed to the next execution (I = 3).
for i in range(10):
if i == 2:
break
print i
When the loop reaches I = 2, the if condition is true, the break is triggered, and the entire loop is stopped.
conclusion
Range ()
For element in sequence:
While conditions:
The continue
break