Python for...else... syntax

for…else…

grammar

for i in range(10):
    break
print('normal end')

for i in range(10):
    break
else:
    print('break else end')

for i in range(10):
    pass
else:
    print('pass else end')

Output result

normal end
pass else end

As can be seen from the above example, only the for loop does not break before entering the else.

scenes to be used

The for...else feature is simple and clear. What are the specific usage scenarios?

Assuming such a requirement, define a function, input n lists, and output the number of lists with all values ​​greater than 0.

First look at the most commonly used methods:

Define a flag, for loop, modify the value of flag...

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def t1(*lists):
    count = 0
    for li in lists:
        flag = True
        for i in li:
            if i < 0:
                flag = False
                break
        if flag:
            count += 1
    return count

If you use the for...else grammar, you can save the annoying flag, which looks a lot more refreshing.

def t2(*lists):
    count = 0
    for li in lists:
        for i in li:
            if i < 0:
                break
        else:
            count += 1
    return count

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/108711697