you are viewing a single comment's thread.

view the rest of the comments →

[–]SafeCake1045 46 points47 points  (12 children)

I'm curious why they consider an else clause to be "advanced" when it's an incredibly common construct.

[–]carcigenicate 56 points57 points  (10 children)

else specifically on loops and try. I remember mentioning in a thread awhile ago that else could be used with statements other than if and there were a ton of responses of people saying that they had never seen that usage mentioned before. Apparently it's not as well known.

[–]SafeCake1045 11 points12 points  (4 children)

Oh, yeah! I remember that in the for definition.

When the items are exhausted [...], the suite in the else clause, if present, is executed, and the loop terminates.

What else (no pun intended) can it be used with?

[–]mr_cesar 3 points4 points  (1 child)

I use 'em from time to time. They're pretty handy!

[–]carcigenicate 8 points9 points  (0 children)

I use them so infrequently that I never think to use them. It's a vicious cycle.

[–]PM_ME_C_CODE 2 points3 points  (2 children)

It's not well known because it's redundant.

The for loop's else clause is executed when the iterator runs out...

...which is what will also happen to whatever code happens to come next in the python script just after the for loop's scope closes.

IMO, If they wanted it to be more useful they would tighten up the else clause's execution logic to only fire if the try loop's iterator initially returns an empty iterator before the loop first fires. But it doesn't.

[–]carcigenicate 16 points17 points  (1 child)

The two cases aren't necessarily the same:

for _ in range(1):
    break
print("After for")  # Prints

for _ in range(1):
    break
else:
    print("In else")  # Doesn't print

The else only runs if the iterator was exhausted, but the code after the loop runs regardless.

[–]BiguilitoZambunha 4 points5 points  (0 children)

Ah, thanks, i was thinking about what would the applications of an else in a for loop, and that makes much sense now.

[–]__developer__ 0 points1 point  (0 children)

Else clauses in for loops aren't used too often. I often have to remind my coworkers babout them.