for what are for/while else clauses
Bengt Richter
bokr at oz.net
Mon Nov 17 15:46:24 EST 2003
On Fri, 14 Nov 2003 19:31:08 +0100, "Diez B. Roggisch" <deets_noospaam at web.de> wrote:
>Hi,
>
>today I rummaged through the language spec to see whats in the for ... else:
>for me. I was sort of disappointed to learn that the else clauses simply
>gets executed after the loop-body - regardless of the loop beeing entered
>or not.
>
>So where is an actual use case for that feature?
>
>I imagined that the else-clause would only be executed if the loop body
>wasn't entered, so I could write this
>
>for r in result:
> print r
>else:
> print "Nothing found, dude!"
>
>instead of
>
>if len(result):
> for r in result
> print r
>else:
> print "Nothing found, dude!"
>
>
>
>waiting for enlightment,
>
My mnemonic is to think of the mysterious elses as coming after prefixed pseudo-code like:
if this_code_is_interfered_with:
<loop code or try block>
else: # got to end of loop or end of try block without interference
hence
>>> for x in []: pass
... else: print 'got to end of nothing without interference ;-)'
...
got to end of nothing without interference ;-)
>>> try: pass
... except: pass
... else: print 'got to end of try: without interference.'
...
got to end of try: without interference.
>>> while raw_input('while> '):
... if raw_input('break? ')=='y': break
... else: print 'got to end of while w/o interference'
...
while> asdad
break? asad
while> asdasd
break?
while>
got to end of while w/o interference
>>> while raw_input('while> '):
... if raw_input('break? ')=='y': break
... else: print 'got to end of while w/o interference'
...
while> asd
break? y
Regards,
Bengt Richter
More information about the Python-list
mailing list