This article and we share the main is the Python cycle of the most error-prone syntax, a look at it, hope to learn Python to help you.
The difference and effect of break and continue under cyclic statements
Break and continue are used to control the loop structure, mainly to stop the loop.
· Break
Break is used to completely end a loop and jump out of the loop body to execute the statement following the loop.
for x in range (10):
if x = = 5:
Break
Print (x) print (' For loop termination ')
The break loop does not terminate until the loop condition is false, and the print result is:
01234 for loop termination
· Continue
Continue and break are a bit similar, except that continue terminates the loop, and then executes the subsequent loop, and break terminates the loop completely.
for x in range(10):
if x = = 5:
Continue
Print (x) print (' For loop ended ')
It can be understood that continue is skipping the remaining statements in the secondary loop, performing the next loop. Printing results are:
012346789 for loop is over.
Similarly, the above also applies to While...else:
else usages in a looping statement
The for and while loops in Python have an optional else branch (such as an optional else branch in the IF statement) that executes after the loop iteration is completed normally. means that the normal loop exits, the Else branch is executed, that is, there is no break statement in the loop body, no return statement, or no exception appears.
· An example of a normal exit loop:
for I in range (5):
Print (i)else:
Print (' normal exit loop ')
#打印结果
0
1
2
3
4
Normal exit cycle
The above loop is completed normally, so the Else branch is executed and the normal loop is printed.
· An example of an exception exit loop:
for I in range (5):
if i==2:
Break
Print (i)else:
Print (' Abnormal exit loop ')
#打印结果
0
1
Terminates the loop with the break statement, the Else branch is not executed, so the "exception exit" is not printed
Similarly, the above also applies to While...else:
Source: Pinterest
What are the common syntax errors for Python loops?