2011-12-16

Explaining For/Else In Python

In response to a thread on G+ I've decided to write a this article on 'how for/else works'.

I should start by saying that this isn't intuitive or simple. It's quite complicated, but it has a very clear use case. Let me start by stating as simply as I can the use-case.

for element in seq:
    if somecondition(element):
         dosomething(element) 
         break
else: 
     dosomething(defaultinput)

I think that example is reasonably clear, but it's important to explain what's happening here.

If a 'for' loop does not break, it's else is run, otherwise the else is not run. So:

  • The else suite is run if:
    • the sequence is empty
    • break is never executed
  • The else suite is bypassed if:
    • break is executed
    • a return statement in the loop is executed
    • an exception raises in the for loop

I hope that's clear. Any comments or addendums or errors I've made, please let me know in the comments.

Edit: I don't think using an 'else:' on a for loop is a bad idea. But I think it should only be used in exactly the idiom presented in the example, anything with more complicated flow control or more than 8 lines should be re-factored to use a function call with 'return' in the appropriate places.

13 comments:

Anonymous said...

The example works but it would probably be more useful to describe why this is extremely bad style and should be avoided, wouldn't it?

geoffrey said...

It should be a syntax error to use else: without a comment on the line saying "WARNING: else doesn't mean what you probably think it does."

Marien Zwart said...

Is this language feature really disliked this much? I use it a lot and it does exactly what I think it does: if the end of the loop ("for" and "while" both support this) is reached without hitting "break", the "else" clause runs. Which is useful for finding an interesting element and doing something else (like complaining) if it's missing.

What's tripping people up? Are you expecting the "else" to only run if the loop body never executed?

Zoe Wolfe said...

College authority need to a best college paper writing service provider person. You can all time communication with your nearest college. If you think you are the perfect on this position.

Freya West said...

Discover English idiomatic expression and phrases with complete meaning, sample examples and origin facts, arranged in very simple cataloging structure like search and alphabetically listing, idioms.in makes it easier to find your idiom.

Joshua dollar said...

We are a team of assignment experts; I got lot of information from your blog. You have done amazing job! . Online Homework Help.

ahmed said...

Ideal Corner Pest Control Co. in Dammam has many and many services provided to its valued customers offering the best service of insect control for all types of insects, rodents and reptiles.
شركة مكافحة حشرات
شركة مكافحة النمل الابيض بالخبر
شركة مكافحة حشرات بالخبر
شركة رش مبيدات بالخبر

Bella said...

This Is Really Great Work. Thank You For Sharing Such A Useful Information Here In The Blog.
Paperssolution
studyhawks
pay someone to do assignment
write my essay
eduhawks
topgradepapers
Assignment Help
<a href="https://liveassignmenthelp.com/>Assignment Help</a>

INTRADOTE (**OFFICIAL**) said...

tndte

Ideal Assignment Help said...

Ideal Assignment Help mainly focuses on offering you the best of the services regarding Assignment Help at the most reasonable price. Our IdealAssignmentHelp nursing assignment help Experts help to complete your assignment within a given deadline. Nursing is an important part of health care sector and it requires the students to develop a cultural competence along with the knowledge of professionalism.

Best Furnace Repair said...

Thanks for keeping people up on what's happening.

Best Furnace Repair

Andy Alvin said...

Avail the best marks and spencer case study answers, Accounting homework helper and Shell SWOT analysis at MyAssignmentHelp. We are a wide range of experts available 24*7 to assist students around the globe.

Online Assignment Help said...

Do you wonder how to write a dissertation methodology sample that supports you in moving forward with your writing? Well, you don’t have to! You have MyAssignmenthelp.com that offers you the most professional dissertation writing services at all academic levels.