当前位置:网站首页>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+=1Variables 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+=1First, 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 :

边栏推荐
- Getting started with postman -- built-in dynamic parameters, custom parameters and assertions
- Collections SQL communes
- 使用dnSpy對無源碼EXE或DLL進行反編譯並且修改
- Transformer structure analysis and the principle of blocks in it
- Kernel symbol table
- Talk about daily newspaper design - how to write a daily newspaper and what is the use of a daily newspaper?
- What if the Flink SQL client exits and the table is emptied?
- Goodbye 2021, how do programmers go to the top of the disdain chain?
- Après 90 ans, j'ai démissionné pour démarrer une entreprise et j'ai dit que j'allais détruire la base de données Cloud.
- Advanced technology management - how to examine candidates in the interview and increase the entry probability
猜你喜欢

No more! Technical team members resign collectively

90 後,辭職創業,說要卷死雲數據庫

Hcie security Day11: preliminarily learn the concepts of firewall dual machine hot standby and vgmp

Common SQL sets

Install and use Chrony, and then build your own time server

Redis concludes that the second pipeline publishes / subscribes to bloom filter redis as a database and caches RDB AOF redis configuration files

MySQL——JDBC

Getting started with postman -- built-in dynamic parameters, custom parameters and assertions

Leetcode daily question 540 A single element in an ordered array Valentine's Day special article looking for a single dog in a pile of lovers ~ the clown is myself

MySQL——JDBC
随机推荐
No matter how hot the metauniverse is, it cannot be separated from data
Talk about daily newspaper design - how to write a daily newspaper and what is the use of a daily newspaper?
MySQL——JDBC
Solve the problem that openocd fails to burn STM32 and cannot connect through SWD
Nacos common configuration
Preliminary understanding of C program design
Basic number theory -- Chinese remainder theorem
仿网易云音乐小程序
Is it OK for fresh students to change careers to do software testing? The senior answered with his own experience
How to choose cache read / write strategies in different business scenarios?
What is the maximum number of concurrent TCP connections for a server? 65535?
Qualcomm platform WiFi update disconnect end open event
(5) Web security | penetration testing | network security operating system database third-party security, with basic use of nmap and masscan
Capture de paquets et tri du contenu externe - - autoresponder, composer, statistiques [3]
"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
鹏城杯 WEB_WP
Design e-commerce seckill system
QT6 QML book/qt quick 3d/ Basics
Such as the visual appeal of the live broadcast of NBA Finals, can you still see it like this?
[Yugong series] go teaching course 002 go language environment installation in July 2022