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

前端 未结 21 1919
爱一瞬间的悲伤
爱一瞬间的悲伤 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:24

    I agree, it's more like an 'elif not [condition(s) raising break]'.

    I know this is an old thread, but I am looking into the same question right now, and I'm not sure anyone has captured the answer to this question in the way I understand it.

    For me, there are three ways of "reading" the else in For... else or While... else statements, all of which are equivalent, are:

    1. else == if the loop completes normally (without a break or error)
    2. else == if the loop does not encounter a break
    3. else == else not (condition raising break) (presumably there is such a condition, or you wouldn't have a loop)

    So, essentially, the "else" in a loop is really an "elif ..." where '...' is (1) no break, which is equivalent to (2) NOT [condition(s) raising break].

    I think the key is that the else is pointless without the 'break', so a for...else includes:

    for:
        do stuff
        conditional break # implied by else
    else not break:
        do more stuff
    

    So, essential elements of a for...else loop are as follows, and you would read them in plainer English as:

    for:
        do stuff
        condition:
            break
    else: # read as "else not break" or "else not condition"
        do more stuff
    

    As the other posters have said, a break is generally raised when you are able to locate what your loop is looking for, so the else: becomes "what to do if target item not located".

    Example

    You can also use exception handling, breaks, and for loops all together.

    for x in range(0,3):
        print("x: {}".format(x))
        if x == 2:
            try:
                raise AssertionError("ASSERTION ERROR: x is {}".format(x))
            except:
                print(AssertionError("ASSERTION ERROR: x is {}".format(x)))
                break
    else:
        print("X loop complete without error")
    

    Result

    x: 0
    x: 1
    x: 2
    ASSERTION ERROR: x is 2
    ----------
    # loop not completed (hit break), so else didn't run
    

    Example

    Simple example with a break being hit.

    for y in range(0,3):
        print("y: {}".format(y))
        if y == 2: # will be executed
            print("BREAK: y is {}\n----------".format(y))
            break
    else: # not executed because break is hit
        print("y_loop completed without break----------\n")
    

    Result

    y: 0
    y: 1
    y: 2
    BREAK: y is 2
    ----------
    # loop not completed (hit break), so else didn't run
    

    Example

    Simple example where there no break, no condition raising a break, and no error are encountered.

    for z in range(0,3):
         print("z: {}".format(z))
         if z == 4: # will not be executed
             print("BREAK: z is {}\n".format(y))
             break
         if z == 4: # will not be executed
             raise AssertionError("ASSERTION ERROR: x is {}".format(x))
    else:
         print("z_loop complete without break or error\n----------\n")
    

    Result

    z: 0
    z: 1
    z: 2
    z_loop complete without break or error
    ----------
    

提交回复
热议问题