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

Magnus Lycka magnus@thinkware.se
Sat Jan 18 18:35:01 2003


At 22:09 2003-01-18 +0000, ahimsa wrote:
>Could someone help me to understand - and even debug - the following. It
>is verbatim of 4.4 of the Python Tutorial Release 2.2.2

No, it's not! ;)

> >>> 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:


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se