Why does python use 'else' after for and while loops?

前端 未结 21 1914
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:57

I understand how this construct works:

for i in range(10):
    print(i)

    if i == 9:
        print(\"Too big - I\'m         


        
21条回答
  •  一整个雨季
    2020-11-21 07:40

    It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

    found_obj = None
    for obj in objects:
        if obj.key == search_key:
            found_obj = obj
            break
    else:
        print('No object found.')
    

    But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

    def find_obj(search_key):
        for obj in objects:
            if obj.key == search_key:
                return obj
    

    Or use a list comprehension:

    matching_objs = [o for o in objects if o.key == search_key]
    if matching_objs:
        print('Found {}'.format(matching_objs[0]))
    else:
        print('No object found.')
    

    It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

    See also [Python-ideas] Summary of for...else threads

提交回复
热议问题