problems with a for loop (noobie)

Sean 'Shaleh' Perry shalehperry at attbi.com
Sat Jul 6 15:54:38 EDT 2002


On 06-Jul-2002 Charles Mantha wrote:
> 
>> > ps : and for some reason, the output is not the same as in the tutorial
>>> when
>> > I try this.
>>
>> This is kind of hard to explain if we don't see the output that you saw.
>> Are you certain you typed it exactly as it appeared in the tutorial
>> (including indentation)?
> 
> This is what I get :
> 
> 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'
> 

the 'else' belongs to the 'for' not the 'if'.

Observe:

>>> for i in (1,2,3):
...   print i
... else:
...   print "finished"
... 
1
2
3
finished


the else is reached when the for finishes UNLESS a break was used to stop the
for loop early.





More information about the Python-list mailing list