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.
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
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!