basic python question about for loop
Diez B. Roggisch
deets at nospam.web.de
Wed Apr 9 17:25:47 EDT 2008
jmDesktop schrieb:
> On Apr 9, 4:58 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>> jmDesktop schrieb:
>>
>>
>>
>>
>>
>>> From the Python.org tutorial:
>>>>>> 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
>>> first time 2 mod 2, 2/2, no remainder == 0, what am I doing wrong?
>>> Why did it fall through?
>> print out what range(2, n) for n == 2 is.
>>
>> And if you didn't know - 2 *IS* a prime.
>>
>> Diez- Hide quoted text -
>>
>> - Show quoted text -
>
> I do not understand.
for <variable> in <sequence> loops over a sequence. And of course it
doens't if the sequence is empty, because you can't loop over something
that is empty, can't you?
and range(2,2) is the empty sequence.
Diez
More information about the Python-list
mailing list