[Introduction to Python] How to stop the loop using break?

Reference site: [Introduction to Python] How to stop a loop using break?

[Introduction to Python] How to stop the loop using break?

There are two types of Python loop statements, a for statement and a while statement. The for statement repeats the process a certain number of times, and the while statement repeats the process while satisfying specific conditions. It's a convenient syntax that repeats the same process without having to enter it over and over, but sometimes you want to get out of the loop statement in the middle. In such a case, you can use the break statement to interrupt the process and get out of the loop statement. This time, I will explain how to use the break statement.

If you want to end the loop processing in the middle, you can use the if statement to do it in a pseudo manner. As an example, suppose you want to examine the elements of a loop and write code that will result in an error if there are numbers greater than 100.

list1 = [24, 55, 32, 65, 74, 120, 72, 67]

loop_flag = 0

for num in list1:
    if(loop_flag == 0):
        if(num < 100):
            print(num)
        else:        
            loop_flag = 1
    

if(loop_flag == 1):    
    print('Error: Invalid number found')

Execution result

24 55 32 65 74 Error: Invalid number found

In this example, a flag (loop_flag) for whether to continue the loop is prepared, and when a number that satisfies the condition appears, the flag is set to 1 so that the processing inside the loop is not executed. This method seems to break the loop at first glance, but in reality it is very wasteful and the code is long just to do nothing in the middle. In such a case, use a break statement.

list1 = [24, 55, 32, 65, 74, 120, 72, 67]

for num in list1:
    if(num >= 100):
        print('Error: Invalid number found')
        break
    
    print(num)

Execution result

24 55 32 65 74 Error: Invalid number found

The execution result is exactly the same as before, but using break is shorter and easier to see. The break statement is mainly used with the if statement in the loop statement. If a specific condition is met in the if statement, the break statement is used to break the loop in the middle and break out. All the syntax after the break statement is skipped, so when displaying an error statement etc., write it before the break statement.

break statement in while statement

It is a break statement that breaks the loop in the middle, but of course it can also be used in a while statement.

list1 = [24, 55, 32, 65, 74, 120, 72, 67]

index = 0

while(index < len(list1)):
    if(list1[index] >= 100):
        print('Error: Invalid number found')
        break
    
    print(list1[index])
    index += 1

Execution result

24 55 32 65 74 Error: Invalid number found

I replaced the for statement with a while statement, but the usage of the break statement is the same. Of course, the result will be the same.

else clause and break statement

Like the if statement, Python's for and while statements have else clauses. The else clause of the loop statement is executed if the iteration ends successfully. For example, if you want to display a message telling you that the loop statement has ended after you have cycled through the loop statement, you would do the following:

list1 = [24, 55, 32, 65, 74, 120, 72, 67]

index = 0

for num in list1:
    print(num)
else:
    print('The loop is complete.')

Execution result

24 55 32 65 74 120 72 67 The loop is complete.

It is a very convenient else clause because it can be processed only once in the same loop block, but it is not actually executed when the break statement breaks the loop.

list1 = [24, 55, 32, 65, 74, 120, 72, 67]

index = 0

for num in list1:
    if(num >= 100):
        print('Error: Invalid number found')
        break
    
    print(num)

else:
    print('The loop is complete.')

Execution result

24 55 32 65 74 Error: Invalid number found

As in the previous examples, if a number of 100 or more is found, an error will occur and the loop will be broken. Then, the last else clause is not executed and the message "Loop completed" is not displayed.

If you use break and else, you can easily "determine whether or not you have broken and perform a specific process only when it is not."

Normally, prepare a variable to determine whether it has broken, and check the contents of the variable with an if statement to determine whether it has broken. It's a hassle because it increases useless variables. If it is an else clause, you only have to write the processing to be performed only when there is no break in it. You don't need useless variables or if statements.

Recommended Posts

[Introduction to Python] How to stop the loop using break?
[Introduction to Python] How to iterate with the range function?
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
[Introduction to Python] How to write repetitive statements using for statements
How to install python using anaconda
[Introduction to Python] How to parse JSON
How to get the Python version
[Python] How to import the library
[Introduction to Python] How to write conditional branches using if statements
[Introduction to Python] How to get data with the listdir function
[Introduction to Python] How to use class in Python?
Introduction to Discrete Event Simulation Using Python # 1
[Introduction to Python] How to split a character string with the split function
How to get followers and followers from python using the Mastodon API
[Introduction to Python] How to use the in operator in a for statement?
Introduction to Discrete Event Simulation Using Python # 2
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Introduction to Python] How to write a character string with the format function
How to use the C library in Python
Introduction to Python Let's prepare the development environment
[Introduction to Udemy Python3 + Application] 23. How to use tuples
[Python] How to change the date format (display format)
[Introduction to Python] How to handle JSON format data
[Introduction to Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
[Algorithm x Python] How to use the list
Introduction to Python with Atom (on the way)
How to get the files in the [Python] folder
How to make Substance Painter Python plugin (Introduction)
[Introduction to Algorithm] Find the shortest path [Python3]
How to install Python
Introduction to Python language
Introduction to OpenCV (python)-(2)
[2015/11/19] How to register a service locally using the python SDK on naoqi os
[Introduction to Python] How to get the index of data with a for statement
[Python] How to remove duplicate values from the list
How to retrieve the nth largest value in Python
[Introduction to Python] How to use while statements (repetitive processing)
How to get the variable name itself in python
Think about how to program Python on the iPad
How to write a GUI using the maya command
How to get the number of digits in Python
How to set up a Python environment using pyenv
How to know the current directory in Python in Blender
How to auto-submit Microsoft Forms using python (Mac version)
[Reintroduction to python] How to import via the parent directory
How to use the Raspberry Pi relay module Python
[Python] How to specify the download location with youtube-dl
[Python] How to use the graph creation library Altair
How to make a Python package using VS Code
Write data to KINTONE using the Python requests module
How to exit when using Python in Terminal (Mac)
[Python] Summary of how to specify the color of the figure
How to use the model learned in Lobe in Python
How to retrieve multiple arrays using slice in python.
[Python] How to rewrite the table style with python-pptx [python-pptx]
How to execute a command using subprocess in Python
How to enjoy Python on Android !! Programming on the go !!
[Introduction to Python] Basic usage of the library matplotlib
[Python] How to output the list values in order