[Tutor] lession 4.4 on finding prime number was: (no subject)

vy vy0123 at gmail.com
Sat May 30 11:52:00 CEST 2009


> Date: Fri, 29 May 2009 09:46:17 -0500
> From: Gregory Morton <tyetheczar at hotmail.com>
> To: Tutor Newsgroup Python <tutor at python.org>
> Subject: [Tutor] (no subject)
> Message-ID: <SNT115-W545DBF8E90942490EBC08D4510 at phx.gbl>
> Content-Type: text/plain; charset="iso-8859-1"
>
>
> I'm having a problem understanding how this code works in lesson 4.4 on the python tutorial. Can anyone explain it in easy-to-digest details? I kind of know what most of the stuff means, but I can't comprehend how it all works in unison. That, and I'm having a hard time understanding what break does.

There is an outer for-loop and an inner for-loop, the pair of numbers
as both for-loops are stepped can be shown by:

>>> for outer in range(2,10):
...	for inner in range(2,outer):
...		print outer,inner

3 2
4 2
4 3
5 2
5 3
5 4
6 2
6 3
6 4
6 5
7 2
7 3
7 4
7 5
7 6
8 2
8 3
8 4
8 5
8 6
8 7
9 2
9 3
9 4
9 5
9 6
9 7
9 8
... ... ...

## [in the example given]
## n steps through the out-loop and x steps through the inner loop;

## intuitively, the outer loop cycles once and the inner loop cycles
## to a size limit (in growing cycles) for each step of n of the outer loop

## the `break' means to end the cycle through the inner loop
## as a consequence of
## the if conditional eliminating the n value as a composite number
## then the next n is used and the inner loop starts from 2 again

## if the if conditional is never met by the inner loop; that n value
is considered
## a prime number

> for n in range(2, 10):
> ...     for x in range(2, n):
> ...         if n % x == 0:
> ...             print(n, 'equals', x, '*', n//x)
> ...             break
> ...     else:
> ...         # loop fell through without finding a factor
> ...         print(n, 'is a prime number')
> ...
> 2 is a prime number
> 3 is a prime number
> 4 equals 2 * 2
> 5 is a prime number
> 6 equals 2 * 3
> 7 is a prime number
> 8 equals 2 * 4
> 9 equals 3 * 3Thanks for all your help,Greg

Hope that helps.

-- Van Ly


More information about the Tutor mailing list