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


i understand how construct works:

for in range(10):     print(i)      if == 9:         print("too big - i'm giving up!")         break; else:     print("completed successfully") 

but don't understand why else used keyword here, since suggests code in question runs if for block not complete, opposite of does! no matter how think it, brain can't progress seamlessly for statement else block. me, continue or continuewith make more sense (and i'm trying train myself read such).

i'm wondering how python coders read construct in head (or aloud, if like). perhaps i'm missing make such code blocks more decipherable?

it's strange construct seasoned python coders. when used in conjunction for-loops means "find item in iterable, else if none found ...". in:

found_obj = none obj in objects:     if obj.key == search_key:         found_obj = obj         break else:     print 'no object found.' 

but anytime see construct, better alternative either encapsulate search in function:

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

or use list comprehension:

matching_objs = [o o in objects if o.key == search_key] if matching_objs:     print 'found', matching_objs[0] else:     print 'no object found.' 

it not semantically equivalent other 2 versions, works enough in non-performance critical code doesn't matter whether iterate whole list or not. others may disagree, avoid ever using for-else or while-else blocks in production code.

see [python-ideas] summary of for...else threads


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -