[Introduction to Python] What is the method of repeating with the continue statement?

Reference site: [Introduction to Python] How to repeat with continue statements?

[Introduction to Python] What is the method of repeating with the continue statement?

Python loop statements are useful for doing the same thing over and over again. Although it is such a loop statement, I think that there are times when you want to execute it only under certain conditions and skip it at other times. In such a case, it is convenient to use the continue statement. This time, I will explain how to use the continue statement.

The continue statement is used in repetitive processes such as for statements. If you use the continue statement, the subsequent processing is skipped without being executed, and you proceed to the next loop.

list1 = [1, 5, 6, 2, 4, 9, 11, 3]

for number in list1:
    if(number < 5):
        continue
        
    print(number)

Execution result

5 6 9 11

This example takes elements from the list of integers and displays only those elements greater than 5. At that time, if the number is less than 5, the continue statement is executed. When the continue statement is executed, the contents after that are skipped and the next loop is started. Therefore, if the last element is less than 5, the last print () will be skipped and will not be displayed.

In the case of simple processing, it can be realized by if-else statements and exceptions, but the longer the code, the harder it is to see and the more complicated it becomes. If you want to skip processing in a loop statement, you can use the continue statement.

continue statement in while statement

Earlier, I used the continue statement in the for statement, but you can use the continue statement in the same way in the while statement, which is the same loop.

list1 = [1, 5, 6, 2, 4, 9, 11, 3]

index = 0

while index < len(list1):
    if(list1[index] < 5):
        index += 1
        continue
        
    print(list1[index])
    index += 1

Execution result

5 6 9 11

This is a replacement of the for statement with a while statement. It's a bit complicated, but it's exactly the same as the for statement in that if the number of elements is less than 5, the continue statement is executed and all the rest of the processing is skipped.

Exit multiple loops with continue statement

In Python, the break statement is provided as a syntax to exit the loop statement from the middle.

for x in range(100):
    if(x == 50):
        print('Exited the loop statement (number of loops:{}Times)'.format(x))
        break

Execution result

Exited the loop statement (loop count: 50 times)

This for statement repeats the loop 100 times, but when the number of loops reaches 50 in the if statement, the break statement breaks the loop. You can easily break a loop with a break statement. However, in the case of a break statement, even if you can exit one loop, you cannot exit multiple loops.

list1 = [ [1,5,7], [10,3, 4], [6, 8, 5]]

for list1_item in list1:
    for item in list1_item:
        print(item)
        if(item >= 10):
            print('Found more than 10 numbers')
            break

Execution result

1 5 7 10 Found more than 10 numbers 6 8 5

In this example, the contents of the two-dimensional list are referenced in multiple loops, and if there are 10 or more elements, the display ends there. However, the break statement can only break one loop. Therefore, in this example, only the inner loop is exited, so the entire loop does not end.

In fact, Python doesn't provide a way to get out of multiple loops. If you want to get out of multiple loops at once, you have to think about the implementation yourself. There are several ways to do this, but in fact, you can get out of multiple loops at once by combining the continue statement and the else clause, which is familiar in the if statement.

list1 = [ [1,5,7], [10,3, 4], [6, 8, 5]]

for list1_item in list1:
    for item in list1_item:
        print(item)
        if(item >= 10):
            print('Found more than 10 numbers')
            break
    else:  #Note that this is not an if but an else of the inner for statement
        continue
    break

Execution result

1 5 7 10 Found more than 10 numbers

With this method, I was able to get out of the loop cleanly. First, we turn the inner for statement, but at the end there is an else clause. The else clause of the for statement is executed last after the loop ends. At the end of the inner loop, we move to the else clause and execute the continue statement. The continue statement is executed and the last break is skipped so the loop continues. If the if statement is executed in the inner loop (in this example, a number of 10 or more is found), break exits the inner loop statement, so the else clause is not executed. Therefore, the final break is executed and the entire loop can be exited.

Recommended Posts

[Introduction to Python] What is the method of repeating with the continue statement?
[Introduction to Python] How to get the index of data with a for statement
[Python] What is a with statement?
[Introduction to Python] What is the most powerful programming language now?
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
[Introduction to Python] What is the difference between a list and a tuple?
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Introduction to Python] How to sort the contents of a list efficiently with list sort
Introduction to Python with Atom (on the way)
[Introduction to Udemy Python 3 + Application] 54. What is Docstrings?
What you want to memorize with the basic "string manipulation" grammar of python
[Introduction to Python] How to iterate with the range function?
[Chapter 5] Introduction to Python with 100 knocks of language processing
What is the true identity of Python's sort method "sort"? ??
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Introduction to Python] Basic usage of the library matplotlib
[Chapter 4] Introduction to Python with 100 knocks of language processing
[Introduction to Python] What is the recommended way to install pip, a package management system?
What to do if the progress bar is not displayed in tqdm of python
I tried to find the entropy of the image with python
[Introduction to Udemy Python3 + Application] 42. for statement, break statement, and continue statement
[Introduction to Udemy Python3 + Application] 39. while statement, continue statement and break statement
What I did to welcome the Python2 EOL with confidence
Try to automate the operation of network devices with Python
What is the default TLS version of the python requests module?
[Introduction to Python] How to get data with the listdir function
Get the source of the page to load infinitely with python.
[Introduction to statistics] What kind of distribution is the t distribution, chi-square distribution, and F distribution? A little summary of how to use [python]
[Python] What is @? (About the decorator)
[python] What is the sorted key?
Python for statement ~ What is iterable ~
What to do with PYTHON release?
What is the python underscore (_) for?
IPynb scoring system made with TA of Introduction to Programming (Python)
March 14th is Pi Day. The story of calculating pi with python
[Introduction to Python] How to split a character string with the split function
[Python] PCA scratch in the example of "Introduction to multivariate analysis"
[Introduction to Python] I compared the naming conventions of C # and Python.
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
I want to output the beginning of the next month with Python
Output the contents of ~ .xlsx in the folder to HTML with Python
[Introduction to Python] How to use the in operator in a for statement?
I tried to improve the efficiency of daily work with Python
How to utilize Python with Jw_cad (Part 1 What is external transformation)
What to do when the value type is ambiguous in Python?
PhytoMine-I tried to get the genetic information of plants with Python
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
[Python] What is pip? Explain the command list and how to use it with actual examples
What to do when a part of the background image becomes transparent when the transparent image is combined with Pillow
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
[Introduction to Udemy Python3 + Application] 33. if statement
[Introduction to Udemy Python3 + Application] 13. Character method
Check the existence of the file with python
What kind of programming language is Python?
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
What is the cause of the following error?
Easy introduction of speech recognition with Python
[Introduction to Python] Let's use foreach with Python