Why does python use 'else' after for and w

2018-12-31 05:16发布

I understand how this construct works:

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

    if i == 9:
        print("Too big - I'm giving up!")
        break;
else:
    print("Completed successfully")

But I don't understand why else is used as the keyword here, since it suggests the code in question only runs if the for block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can't progress seamlessly from the for statement to the else block. To me, continue or continuewith would make more sense (and I'm trying to train myself to read it as such).

I'm wondering how Python coders read this construct in their head (or aloud, if you like). Perhaps I'm missing something that would make such code blocks more easily decipherable?

19条回答
弹指情弦暗扣
2楼-- · 2018-12-31 06:01

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

查看更多
大哥的爱人
3楼-- · 2018-12-31 06:01

Let us suppose we have a function

def broken(x) : return False if x==5 else True

Which means that only 5 is not broken. Now in case broken is never evaluated with 5:-

for x in range(4):
    if not broken(x) : break
else:
    print("Everything broken... doom is upon us")

Will give output:-

Everything broken... doom is upon us

Where when broken is evaluated with 5:-

for x in range(6):
    if not broken(x) : break
else:
    print("Everything broken... doom is upon us")

It will not print anything. Thus indirectly telling there is at least something which is not broken.

However, in case you want to cheat and skip something you found was broken. That is, continue the loop even though you found 5 as broken, else statement will still be printed. That is :-

for x in range(6):
    if not broken(x) : continue
else:
    print("Everything broken... doom is upon us")

Will print

Everything broken... doom is upon us

I hope it clears the confusion instead of creating a new one :-)

查看更多
余生请多指教
4楼-- · 2018-12-31 06:03

I think documentation has a great explanation of else, continue

[...] it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."

Source: Python 2 docs: Tutorial on control flow

查看更多
有味是清欢
5楼-- · 2018-12-31 06:04

The else keyword can be confusing here, and as many people have pointed out, something like nobreak, notbreak is more appropriate.

In order to understand for ... else ... logically, compare it with try...except...else, not if...else..., most of python programmers are familiar with the following code:

try:
    do_something()
except:
    print("Error happened.") # The try block threw an exception
else:
    print("Everything is find.") # The try block does things just find.

Similarly, think of break as a special kind of Exception:

for x in iterable:
    do_something(x)
except break:
    pass # Implied by Python's loop semantics
else:
    print('no break encountered')  # No break statement was encountered

The difference is python implies except break and you can not write it out, so it becomes:

for x in iterable:
    do_something(x)
else:
    print('no break encountered')  # No break statement was encountered

Yes, I know this comparison can be difficult and tiresome, but it does clarify the confusion.

查看更多
君临天下
6楼-- · 2018-12-31 06:05

Codes in else statement block will be executed when the for loop was not be broke.

for x in xrange(1,5):
    if x == 5:
        print 'find 5'
        break
else:
    print 'can not find 5!'
#can not find 5!

From the docs: break and continue Statements, and else Clauses on Loops

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.)

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.

The continue statement, also borrowed from C, continues with the next iteration of the loop:

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
查看更多
低头抚发
7楼-- · 2018-12-31 06:09
for i in range(3):
    print(i)

    if i == 2:
        print("Too big - I'm giving up!")
        break;
else:
    print("Completed successfully")

"else" here is crazily simple, just mean

1, "if for clause is completed"

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

    if i == 2:
        print("Too big - I'm giving up!")
        break;
if "for clause is completed":
    print("Completed successfully")

It's wielding to write such long statements as "for clause is completed", so they introduce "else".

else here is a if in its nature.

2, However, How about for clause is not run at all

In [331]: for i in range(0):
     ...:     print(i)
     ...: 
     ...:     if i == 9:
     ...:         print("Too big - I'm giving up!")
     ...:         break
     ...: else:
     ...:     print("Completed successfully")
     ...:     
Completed successfully

So it's completely statement is logic combination:

if "for clause is completed" or "not run at all":
     do else stuff

or put it this way:

if "for clause is not partially run":
    do else stuff

or this way:

if "for clause not encounter a break":
    do else stuff
查看更多
登录 后发表回答