[docs] 4.4. break and continue Statements, and else Clauses on Loops

Sandro Tosi sandro.tosi at gmail.com
Tue Mar 22 21:54:39 CET 2011


Hi,

On Fri, Mar 11, 2011 at 18:01, Timox@ <timox at gala.net> wrote:
> Hi!
>
> In v2.7 and future versions of Python tutorial.
>
> <print>
> Python 3.1.3 (r313:86834, Mar  8 2011, 08:21:55)
> [GCC 4.4.5] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>>
>>>> for n in range(2, 10):
>
> ...     for x in range(2, n):   # !!! if n = 9 and x = 2 then the output of
> ...             if n % x == 0:    # the condition without further
> verification from the list!!!
> ...                     print(n, 'equals', x, '*', n//x)
> ...                     break
> ...             else:
> ...                     print(n, 'is a prime number')

you cut&pasted the code wrongly; you have:

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')

while it actually is:

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')

(note the 'else' is relative to 'for' not 'if').

Regards,
-- 
Sandro Tosi (aka morph, morpheus, matrixhasu)
My website: http://matrixhasu.altervista.org/
Me at Debian: http://wiki.debian.org/SandroTosi


More information about the docs mailing list