<>1 while loop

<>1.1 General form

while The most complete form of a statement is : The first line and test expression have a body composed of one or more lines of normal indented statements and an optional else part (else
Some will leave the loop without touching the control break Execute on statement ).Python Will always calculate the test of the head , Then execute the statements within the loop body , Until the test returns a false value :
while test: statements else: statements
<>1.2 Examples

The following example will continue to cut off the second part of the string - One character , Until the string is empty and returns false . This directly tests the object , Instead of using a more lengthy equivalent (while x != ' ':)
, It can be said to be a very typical usage :
x='spam' while x: print(x,end=' ') x=x[1:] # spam pam am m
<>2 break,continue,pass And cyclic else

stay Python in :

* break: Jump out of the nearest peripheral loop ( Skip entire loop statement )
* continue: Jump to the head of the nearest peripheral loop ( Come to the head line of the loop )
* pass: Do nothing , It's just a space occupying statement
* loop else block : It will be executed when and only when the cycle leaves normally ( That is, I didn't touch it break sentence ).
<>2.1 General circulation form

join break and continue After statement ,while The general form of the loop is shown below :
while test: statements # Leave the loop directly , not for the time being else sentence if test: break # Re execute the cycle , Not considered else sentence if
test: continue else: statements
break and continue Can appear in while( or for) Anywhere in the loop body , But it is usually further nested in if In the statement , So as to take corresponding actions according to some conditions .

<>2.2 pass

pass Statement is a placeholder statement without operation , When the syntax requires a statement but there is no actual statement to write , You can use it . It is usually used to write an empty body for a compound statement . for example , If you want to write an infinite loop , Do nothing at every iteration , Just write one pass:
while True: pass
Because the body is just an empty statement , therefore Python Will fall into a dead circle . For statements ,pass Almost the same as in the object None equally , It means nothing .

We'll see later pass More meaningful use , For example, ignore try Exception caught by statement , And define an empty class object , Used to carry properties and act in other programming languages “ structural morphology " or “ record ” Role of .pass Often express ” I'll fill it in later ”, That is, temporarily fill the body of the function :
def func1(): pass def func2(): pass
If the function body is empty, you will get a syntax error , So we can use pass To replace .

<>2.3 continue

continue The statement immediately jumps to the top of the loop . in addition , It also helps you avoid statement nesting occasionally . The following example uses continue Skip odd :
x=10 while x: x=x-1 if x%2 != 0: continue print(x,end=' ') # 8 6 4 2 0
Python No, “go to” sentence , But because continue Let the program jump when executing , About use “go
to” Many of the warnings you face about readability and maintainability apply .continue It should be used less , Especially at the beginning of use Python When . for example , If will print Put on if below , Then the previous example may be clearer :
x=10 while x: x=x-1 if x%2 ==0: print(x,end=' ')
<>2.4 break

break Statement causes an immediate exit from a loop . Because I met break Time , be located break The loop body code after is not executed , So sometimes you can introduce beak To avoid nesting . for example , The following is the loop under the interactive command line of Jian'an , isomorphism input input data , User input and “stop” Exit end at :
while True: name=input("Enter name:') if name == 'stop': break age=input(
'Enter age:') print('hello',name'=>',int(age)**2)
<>2.5 Cyclic else

When with circular else When combined with clauses ,break Statement can usually replace the flag bit indicating whether the loop ends normally in other programming languages . for example , The following program searches whether there is a greater than 1 Factor of , To determine a positive integer y Is it a prime number :
x=y//2 while x>1: if y%x==0: print(y,'has facor',x) break x-=1 else: print(y,
'is prime')

In addition to setting the flag bit in the cycle and testing when the cycle exits , You can do the same as above , Use where the factor is found break sentence . therefore , loop else Clauses can be considered to be executed only when no factor is found . If you don't break, Then the number is prime . You can trace this code to see how it works .

If the loop body has never been executed , loop else The clause will also be executed , Because you are not executing in the loop body at this time break sentence . That is to say while In circulation , If the test on the first line - The beginning is false , that else Will also perform . So in . In the above example , If x- Less than or equal to at the beginning 1
( for example , If y yes 2), Then you'll still get “is prime" Information .

<>3 for loop

for Cycle in Python Is a general-purpose sequence iterator : It can traverse elements within any ordered sequence or other iteratable object .for Statements can be used with strings , list , Tuples or other built-in iteratable objects , And then we create new user-defined objects through classes .

<>3.1 General form

Python for The first line of the loop specifies a ( Or some ) Assignment target , And the objects we want to traverse . The first line is followed by the statement block we want to repeat :
for target in object: statements else: statements

When Python function for Cycle time , Iterates objects one by one object The element in is assigned a name target, The body of the loop is then executed for each element . The loop body generally uses the assigned target to refer to the current element in the sequence , It's like it's a cursor that traverses a sequence .

for The name used as the assignment target in the header line is usually for Variables in the scope of the statement ( It could be new ). The name is nothing special , You can even modify it in the body of the loop , But when control returns to the top of the cycle again , Will automatically be set as the next element in the sequence . After cycle , This variable generally refers to the recently used element , That is, the last element in the sequence , Unless through a break Statement exited the loop .

for Statements are also supported - An optional else block , Its effect is similar to that in while Same in cycle : If the loop leaves without touching break sentence , Will execute (
That is, all elements of the sequence have been accessed ). Previously introduced break Statement and continue Statements can also be used in for In circulation , And while Same cycle .for The complete form of the cycle is as follows :
for target in object: statements if test: break if test:continue else:
statements
<>3.2 Examples
<>3.2.1 Other data types
Any sequence can be used for for loop , because for Loops are a generalization tool . for example ,for Loops can be used for strings and tuples :
S='lumberjack' T=('and','I am','okay') for x in S: print(x,end=' ') # l u m b
e r j a c k for x in T: print(x,end=' ') # and I am okay <>3.2.2 for Tuple assignment in loop
To be added 423

<>3.3 Please pay attention : Document Scanner

<>4 Tips for writing loops

<>4.1 Counter cycle :range

<>4.2 Sequence scanning :while and range vs for

<>4.3 Sequence scrambler :range and len

<>4.4 Non exhaustive traversal :range vs Slice

<>4.5 Modify list :range vs deduction

<>4.6 Parallel traversal :zip and map

<>4.7 The offset and element are given at the same time :enumerate

<>4.8 Please pay attention :shell Orders and others

Technology