Python articles --- exit for loop method: break and continue

Python articles --- exit for loop method: break and continue

In fact, the usage of break and continue to exit the for loop is the same as that of exiting while. break, when certain conditions are true, exit the loop, the following code is not executed, and terminate the entire loop; continue, when certain conditions are true, terminate the current loop and then execute the next loop. Let's use 2 code examples to see how to use it and the execution results.

1. break exits the for loop

Code example:

str1 = 'Python自学网'
for i in str1:
    # 当某些条件成立退出循环,后面代码不执行,终止整个循环 ----break----条件:当i取到字符自
    if i == '自':
        break
    print(i)

Results of the:
insert image description here

Second, continue exits the for loop

Code example:

str1 = 'Python自学网'
for i in str1:
    # 当某些条件成立退出循环,后面代码不执行,终止整个循环 ----break----条件:当i取到字符自
    if i == '自':
        continue
    print(i)

Results of the:

insert image description here

eg:

flag = ""


for i in range(10):
    for x in "abc":
        print(i, "---------", x)
        if x == "b":
            flag = True
            break
    if flag:
        break

insert image description here

Guess you like

Origin blog.csdn.net/m0_46825740/article/details/129812769