当前位置:网站首页>Control loop of program (while loop)
Control loop of program (while loop)
2022-07-03 21:36:00 【Leifeng】
Infinite loop :
A condition controlled cyclic operation .
The syntax is as follows :
while < Conditions >:
< Sentence block >
In the above format while Keywords and colons identify while The beginning and end of a statement , Cyclic conditions and while Keywords are separated by spaces , Statement blocks are indented with while Statement generates Association .
perform while When the sentence is , If the value of the cycle condition is True, The statement block in the loop is executed , After executing the statement block, judge the loop condition again , So back and forth , Until the value of the cycle condition is false When the loop terminates , Execute the code after the loop .while The execution flow of the statement is as follows :
Cycle according to this condition , If this condition holds , Then the following statement will be executed , Judge the condition again after execution , If the conditions are still true , She will continue to execute the following sentence , Come back to judge the cycle .
Repeatedly execute the statement block , Until the conditions are not met .
The code example is shown below :
a=3 while a>0: a=a-1 print(a)
The operation interface is as follows :
Code example 2 is shown below :
i=1 result=0 while i<=10: result+=i #result=result+i i+=1 #i=i+1 print(result)
In the above example, the variable i It's a cyclic factor , Its initial value is 1, It will increase with the number of cycles ; Variable result Is the sum of the requirements , Its initial value is 0. First execution while loop , because i<=10 The value of is True, So the code segment in the loop will be executed , send result The value of is determined by 0 Turn into 0+1,i The value of is determined by 1 Turn into 2; Judge again i<=10, So back and forth , until i The value of a 11 when ,i<=10 The value of a False, The loop ends , Execute the print statement after the loop , Output result Value .
The operation interface is as follows :
Cycle control reserved word :
break and continue
break Jump out and end the current loop , Execute the statement after the loop
continue End the current cycle and continue to execute the subsequent cycles .
break and continue It can be done with for and while Use it in a circular way
continue When the sub loop body executes , If continue Reserved words , Then the contemporary cycle will end and go to the next cycle .
break It means that once this reserved word is encountered, the whole cycle ends .
break The sample code is as follows :
for word in "Python": if word=='o': break print(word,end=" ")
Traversing this string python, If o, Then stop printing the string , Out of the loop , That is, the cycle ends .
The operation interface is as follows :
continue The sample code is as follows :
for word in "Python": if word=='o': continue print(word,end=" ")
Traversing this string , If o, Don't print this o, Otherwise, print all other characters .
The operation interface is as follows :
A nested loop :
Loops can be nested with each other , And then realize more complex logic . Loop nesting can be divided into while Loop nesting and for A nested loop .
while A nested loop :
while Loop nesting means while Nested in statement while or for sentence .
The format is as shown below :
while The loop condition 1: # The outer loop
Code segment 1
while The loop condition 2: # Inner circulation
Code segment 2
perform while Loop nesting , If the cycle conditions of the outer cycle 1 The value of is True, Then execute the code snippet 1, And the circulation conditions of inner circulation 2 Judge : If cycle condition 2 The value of is True Then execute the code snippet 2, If it's worth False End the inner loop . After the execution of the inner loop, continue to judge the loop conditions of the outer loop 1, So back and forth , Until the cycle condition 1 The value of is False End the outer cycle .
The code example is as follows :
i=1 while i<6: j=0 while j<i: print("*",end="") j+=1 print() i+=1
Variables in the above example i Represents the number of lines of the graph , Variable j For each line “*” The number of . It should be noted that , Printed by the above program “*” Just wrap the line once , So the code is modified in the inner loop print() Function Terminator ( Pass code print("*",end="") take end Parameter default Terminator '\n' Replace with a space character .
The running code is as follows :
Format 2 is as follows :
while The loop condition 1: # The outer loop
Code segment 1
for Loop variable in Traversal structure # Inner circulation
Code segment 2
The code example is as follows :
i=1 while i<6: j=0 for j in '012345': print("*",end="") print(j)
First of all, for while Cycle to judge the conditions ,i The initial value of 1, Condition is True, Conduct for loop , The string ‘012345’ Each character in it is iterated , Output one by one , At the same time output j.
The operation interface is as follows :
for A nested loop :
for Loop nesting means for Nested in statement while or for sentence .
The format is as shown below :
for Loop variable in Traversal structure : # The outer loop
Code segment 1
for Loop variable in Traversal structure :# Inner circulation
Code segment 2
perform for Loop nesting , The program first accesses the first element of the loop variable in the outer loop 、 Execute code snippets 1、 Access the first element of the loop variable in the inner loop 、 Execute code snippets 2, Then access the next element of the inner loop 、 Execute code snippets 2, So back and forth , Until the loop variable of the inner loop is accessed, the inner loop ends , Instead, continue to access the next element in the outer loop , End the outer loop after accessing the loop variables of the outer loop . therefore , Every time the outer loop is executed , Will execute an inner loop .
The code example is as follows :
for i in range(1,6): for j in range(i): print("*",end='') print()
Operation interface :
Format 2 is as follows :
for Loop variable in Traversal structure # The outer loop
Code segment 1
while The loop condition 1: # The outer loop
Code segment 2
The code is as follows :
for i in range(5): j=1 while i>j: print("*",end='') j+=1 print() i+=1
First, execute the outer loop for loop ,range(5) From 0 Start , Then execute the inner loop ,i=0, After judging ,i The value of is not greater than j Value , That is, the condition is false, Output directly . then i add 1 operation ,i=1, At the same time false, Then the output , cycle , Until all output .
The operation interface is as follows :
In loop nesting , If used break sentence , The program is running to break Statement will end the loop of this layer . namely break Only jump out of the current innermost loop .
The code example is as follows :
S='PYTHON' while S!="": for c in S: if c=='T': break print(c,end='') S=S[:-1]
The operation interface is as follows :
Advanced use of loops :
The expansion of the cycle
Circulation and else
The format is as follows :
for < Loop variable > in < Traversal cycle >:
< Sentence block 1>
else:
< Sentence block 2>
When the cycle is not break When the statement exits , perform else Sentence block .
else The statement block is used as a reward for the normal completion of the loop .
This is a else And exception handling else Similar usage .
The code example is as follows :
for c in "PYTHON": if c=='T': continue print(c,end="") else: print(" The normal exit ")
The operation interface is as follows :
Otherwise, the code example is as follows :
for c in "PYTHON": if c=='T': break print(c,end="") else: print(" The normal exit ")
The operation interface is as follows :
边栏推荐
- 2022-02-15 Daily: 2022 AAAI fellow release
- Set, weakset, map, weakmap in ES6
- Is flush account opening and registration safe and reliable? Is there any risk?
- "Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks
- Talk about daily newspaper design - how to write a daily newspaper and what is the use of a daily newspaper?
- 4. Data splitting of Flink real-time project
- Basic number theory -- Chinese remainder theorem
- "Designer universe" argument: Data Optimization in the design field ultimately falls on cost, safety and health | chinabrand.com org
- Solve the problem that openocd fails to burn STM32 and cannot connect through SWD
- Base ring tree Cartesian tree
猜你喜欢
抓包整理外篇——————autoResponder、composer 、statistics [ 三]
Inventory 2021 | yunyuansheng embracing the road
QT6 QML book/qt quick 3d/ Basics
treevalue——Master Nested Data Like Tensor
(5) User login - services and processes - History Du touch date stat CP
Scientific research document management Zotero
Minio deployment
How to choose cache read / write strategies in different business scenarios?
MySQL - index
Experience summary of database storage selection
随机推荐
(5) User login - services and processes - History Du touch date stat CP
Compilation Principle -- syntax analysis
[Yugong series] go teaching course 002 go language environment installation in July 2022
Memory analyzer (MAT)
Décompiler et modifier un exe ou une DLL non source en utilisant dnspy
@Transactional注解失效的场景
MySQL——JDBC
Mysql - - Index
Remember the experience of automatically jumping to spinach station when the home page was tampered with
Teach you how to install aidlux (1 installation)
Capture de paquets et tri du contenu externe - - autoresponder, composer, statistiques [3]
Kubernetes 通信异常网络故障 解决思路
QT6 QML book/qt quick 3d/ Basics
Pengcheng cup Web_ WP
Yiwen teaches you how to choose your own NFT trading market
4. Data splitting of Flink real-time project
MySQL——SQL注入问题
内存分析器 (MAT)
Such as the visual appeal of the live broadcast of NBA Finals, can you still see it like this?
Read the root directory of the folder, write txt and generate random samples