[Tutor] Else Clause In A Loop

kinuthia muchane muchanek at gmail.com
Mon May 12 18:51:12 CEST 2008


Hi,

I learnt that a loop can have an else clause. And that this clause
executes when the loop TERMINATES. In a while loop when the condition
becomes false, and in a for loop when a sequence is exhausted. When I
write the following code it seems to work:

for n in [1,2,3,4,5]:
	print 'we are in the loop',n
else:
	print 'we are now EXITING the loop',n

which results in:

we are in the loop 1
we are in the loop 2
we are in the loop 3
we are in the loop 4
we are in the loop 5
we are now EXITING the loop 5

Or:

n = 1
while n <= 5:
	print 'we are in the loop',n
	n += 1
else:
	print 'we are now EXITING the loop',n

...which gives:

we are in the loop 1
we are in the loop 2
we are in the loop 3
we are in the loop 4
we are in the loop 5
we are now EXITING the loop 6 (it spills over here!)

This has served to confuse me more. Would someone please kindly explain
how all this fits into the code below which searches (and finds!) for
prime numbers...


def prime():
   number = int(raw_input("Enter a number :"))
   for i in range(2,number):
	for j in range(2,i):
		if i%j == 0:
			break
	else:
		print "is a prime number", i
prime()

...especially in the instance when number is 2 in the first for
statement, for then we will have for j range(2,2)! Or what is going
on?? 

Thanks,
Kinuthia...




More information about the Tutor mailing list