[Tutor] (no subject)
Lie Ryan
lie.1296 at gmail.com
Sat May 30 03:14:39 CEST 2009
Gregory Morton wrote:
> 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.
break exits the for loop immediately even if there is still items that
need to be looped.
The prime finding program's algorithm is by trial division; it tests
whether the number is divisible from 2 to the number itself - 1 (since a
prime number is defined as only divisible by 1 and the number itself).
The for-loop's else suite is executed iff the loop exits normally (i.e.
when range(2, n) is exhausted, i.e. not because of break).
>
> 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 * 3
>
> Thanks for all your help,
> Greg
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list