basic python question about for loop
glasper9 at yahoo.org.au
Sat Apr 12 23:06:30 CEST 2008
"jmDesktop" <needin4mation at gmail.com> wrote in message
news:a6017454-6ac8-44e1-bc56-49709720a666 at e39g2000hsf.googlegroups.com...
> So what is n and x in the first iteration? Sorry. I'm trying.
Remember how Python's range operator works. range(n, x) constructs a list
that consists of all elements starting with n and up to, but /not
including/, x. For example, range(3, 7) constructs the list [3, 4, 5, 6].
So what happens if you try to construct the list range(2, 2)? In this case,
Python will construct an empty list -- this is its interpretation of "up to,
but not including n" for an argument like range(n, n). This is precisely
what is happening in the first iteration of the first enclosing for loop.
Trace through the code; see that 2 is bound to n in the first iteration; see
that the inner loop then tries to construct the list range(2, n), which is
range(2, 2), which is an empty list. And a "for x in " statement will not
execute even once.
As it happens, your loop is perfectly correct. You are testing for divisors
for a number excluding 1 and the number itself. For the number 2, the
number of possible divisors satisfying this condition is an empty set. So 2
is, quite correctly, adjudged to be prime.
More information about the Python-list