Python Tutorial - Break and Continue Statement

Python Exercise Lists

Python – Break Statement

We know that when executing a while loop or a for loop, as long as the loop conditions are met, the program will always execute the loop body and keep spinning. But in some scenarios, we may want to force the loop to end before the loop ends. Python provides two ways to force the current loop body to leave:

  • With the continue statement, you can skip execution of the remaining code in the loop body and execute the next loop.
  • With just the break statement, you can terminate the current loop completely.

This section first explains the use of break, and the continue statement is introduced in the next section for detailed introduction.

The break statement can immediately terminate the execution of the current loop, jumping out of the current loop structure. Whether it is a while loop or a for loop, as long as the break statement is executed, it will directly end the currently executing loop body.

This is like running on the playground. I originally planned to run 10 laps, but when I ran to the second lap, I suddenly thought of something urgent, so I stopped running decisively and left the playground. This is equivalent to using the break statement to terminate early cycle.

The syntax of a break statement is very simple, just add it directly to the corresponding while or for statement. For example in the following program:

website = " http://www.freelearningpoints.com/python/tutorials/python-basic-variable"
# A simple for loop
for i in website:
    if i == ',':
        #Terminate the loop
        break
    print (i, end = "")
print ("\ nExecute code outside the loop")
           

The output is:

http://www.freelearningpoints.com/python/tutorials/python-basic-variable\ nExecute code outside the loop

It is not difficult to analyze the above program. When the loop reaches the comma (,) in the website string, the program executes the break statement, which will directly terminate the current loop and exit the loop body.

The break statement is generally used in combination with the if statement to indicate that the loop body is to be jumped out under certain conditions.

Note that from the previous learning, we know that an else statement can also be provided after the for loop. In this case, if you use the break statement to break out of the loop body, the code contained in the else will not be executed. for example:

website = " http://www.freelearningpoints.com/python/tutorials/python-basic-variable"
for i in website:
    if i == ',':
        #Terminate the loop
        break
    print (i, end = "")
else:
    print ("Execute code in an else statement")
print ("\ nExecute code outside the loop")
           

The output is:

http://www.freelearningpoints.com/python/tutorials/python-basic-variableExecute code in an else statement \ nExecute code outside the loop

It can be seen from the output that after using break to jump out of the current loop body, the else code block after the loop will not be executed. However, if you place the code in the else block directly after the loop body, that part of the code will be executed.

In addition, for nested loop structures, the break statement only terminates the execution of the loop body it is in, and does not affect all loop bodies. for example:

website = " http://www.freelearningpoints.com/python/tutorials/python-basic-variable"
for i in range (3):
    for j in website:
        if j == ',':
            break
        print (j, end = "")
    print ("\ nBreak out of the inner loop")
           

The output is:

http://www.freelearningpoints.com/python/tutorials/python-basic-variable\ nBreak out of the inner loop
http://www.freelearningpoints.com/python/tutorials/python-basic-variable\ nBreak out of the inner loop
http://www.freelearningpoints.com/python/tutorials/python-basic-variable\ nBreak out of the inner loop

Analyzing the above program, whenever the inner loop is executed, as long as it loops to the comma (,) in the website string, it will execute the break statement. It will immediately stop executing the current memory loop body and continue to execute the outer loop.

Then the reader may ask, in the nested loop structure, how to jump out of the inner loop and outer loop at the same time? The easiest way is to borrow a variable of type bool.

Modify the above program:

website = " http://www.freelearningpoints.com/python/tutorials/python-basic-variable"
#Define a bool variable in advance and assign an initial value to it
flag = False
for i in range (3):
    for j in website:
        if j == ',':
            #Before break, modify the value of flag
            flag = True
            break
        print (j, end = "")
    print ("\ nBreak out of the inner loop")
    #Use break again in the outer loop body
    if flag == True:
        print ("Out of the outer loop")
        break
           

The output is:

http://www.freelearningpoints.com/python/tutorials/python-basic-variable\ nBreak out of the inner loop
http://www.freelearningpoints.com/python/tutorials/python-basic-variable\ nBreak out of the inner loop
http://www.freelearningpoints.com/python/tutorials/python-basic-variable\ nBreak out of the inner loop

It can be seen that by using a variable flag of type bool, the value of flag is changed when the inner loop is exited. At the same time, in the outer loop body, it is determined whether the value of the flag has changed. On the contrary, the outer loop continues to execute.

Of course, only 2 levels of nested loops are jumped out. This method supports jumping out of multi-level nested loops.

Python – Continue Statement

Compared with the break statement, the continue statement is not so powerful, it will only terminate the execution of the remaining code in this loop and continue execution directly from the next loop.

Still taking running as an example, the original plan was to run 10 laps, but when I ran for 2 and a half laps, I suddenly received a call. At this point, I stopped running. When I hung up the phone, I did not continue to run the remaining half laps. But start directly from the third lap.

The continue statement is used in the same way as the break statement, as long as it is added at the corresponding position in the while or for statement. Example:

website = " http://www.freelearningpoints.com/python/tutorials/python-basic-variable"
# A simple for loop
for i in website:
    if i == ',':
        # Ignore the remaining statements in this loop
        print ('\ n')
        continue
    print (i, end = "")
           

The output is:

http://www.freelearningpoints.com/python/tutorials/python-basic-variable

As you can see, when you traverse the add string to the comma (,), you will enter the if statement to execute the print statement and continue statement. Among them, the print statement acts as a line feed, and the continue statement causes the Python interpreter to ignore execution of line 8 and start execution directly from the next loop.

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises