How to exit for loop in python

(*-*)浩
Release: 2019-07-09 10:13:35
Original
9904 people have browsed it

The for loop in Python is different from other languages, but exiting the loop is still the same as in most languages. You can use the keyword break to exit the entire for loop.

How to exit for loop in python

The break statement to exit the loop(Recommended learning: Python video tutorial)

The above question, Let’s answer them one by one. Let’s talk about the first question first. In a loop statement, what should we do if we want to exit the loop midway?

The Python language provides the break statement to jump out of the current loop and directly execute the following statements. When using the break statement, a trigger condition is generally set. When the set condition is met, the break statement is executed to exit the loop.

Define mark variables; use changes in variable values ​​to exit the loop

# 第一种嵌套形式
a = [[1, 2, 3], [5, 5, 6], [7, 8, 9]]
# init_i = 0
# init_j = 0
flag = True
for i in range(3):
    for j in range(3):
        # print(i, j)
        if a[i][j] == 5:
            flag = False
            init_i = i
            init_j = j
            break
    if not flag:
        break
print(init_i, init_j)
print(i, j)

# 第二种嵌套形式
flag = True
while flag:
    for i in range(10):
        print(x)
        flag = False
        break
Copy after login

For more Python-related technical articles, please visit Python Tutorial Column for learning!

The above is the detailed content of How to exit for loop in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!