[Tutor] Python Tutorial rel 2.2.2 - need debug for 4.4. Code example

ahimsa ahimsa@onetel.net.uk
Sun Jan 19 05:09:02 2003


On Sat, 2003-01-18 at 23:33, Magnus Lycka wrote:

> No, it's not! ;)
> 

Magnus - you are right!! Thanks. I think what had happened is two
things: 1. as you suggested, I hadn't anticipated an 'else' to be
coupled with a 'for' and just really didn't look at it; and 2. allowed
the auto-indent of my interpreter to control the amount of white-space
allocated to the else which - understandably enough - aligned it with
the 'if' block, and because (I have printed the Tut out) the code runs
over 2 pages I didn't bother to check the alignment with the print out
either.
Two lessons from this:
1. While it might be wise to work towards being a lazy programmer, it is
NOT wise to be careless one
2. When in doubt - ask: my eyes just couldn't pick it up, so thanks.

Have changed the indenting and all works fine ... :)

All the best
Andrew

> > >>> for n in range( 2, 10 ):
> >         for x in range( 2, n ):
> >                 if n % x == 0:
> >                         print n, 'equals', x, '*', n/x
> >                         break
> >                 else:
> >                         print n, 'is a prime number.'
> 
> As Bob pointed out, you have indented the last two lines
> one step too much. I can understand this, since no other
> languages I know of have for-else or while-else loops. I'm
> not sure it was a wise choice to put that feature in Python
> since it's so odd. It's no problem once you are used to it,
> and it's useful now and then, and certainly, if-statement
> are very much like one-pass loops ;), but it might well
> confuse people to begin with...as it did here...
> 
> I can only suggest that you read the section headings more
> carefully the next time:
> 
> "4.4 break and continue Statements, and else Clauses on Loops"
> 
> The text just before the code is also a hint...
> 
> Loop statements may have an else clause; it is executed when the
> loop terminates through exhaustion of the list (with for) or when
> the condition becomes false (with while), but not when the loop
> is terminated by a break statement. This is exemplified by the
> following loop, which searches for prime numbers:
-- 
ahimsa <ahimsa@onetel.net.uk>