no SyntaxError?

Michael Hudson mwh21 at cam.ac.uk
Tue Jun 13 16:28:45 EDT 2000


"Robert W. Bill" <rbill at digisprings.com> writes:

> Just curious- I didn't find any references to this in a quick search of 
> the faq and elsewhere...
> 
> This snippet generates "SyntaxError: invalid syntax"
> 
> def test():
>     else: print "whoops"
> test()
> 
> However, the following snippet generates "0 1 whoops" when it seems like
> it should also generate "SyntaxError: invalid syntax" because there is no 
> if before the else. 
>  
> def test1():
>     for i in range(2):
>         print i,
>     else:
>         print "whoops"
> 
> test1()
> 
> Why is it that I do not get a "SyntaxError" in the second example?

Because it is valid Python!  An else block after a for loop is
executed if the loop exits normally (ie. by getting to the end of the
list), but not if the loop is exited via a break statement.  Same
applies to while loops.

A little used feature (they don't leap to my mind very readily,
certainly).

Cheers,
M.

-- 
  Imagine if every Thursday your shoes exploded if you tied them 
  the usual way.  This happens to us all the time with computers, 
  and nobody thinks of complaining.                     -- Jeff Raskin



More information about the Python-list mailing list