[Tutor] Else Clause In A Loop

"Simón A. Ruiz" sruiz at canterburyschool.org
Mon May 12 20:08:54 CEST 2008


I'll try my hand at this:

The outside for loop is looking through every number up to the variable 
"number".

For each of those numbers, it checks to see if any number between 2 and 
i is divisible into i. If it finds anything, we know it's not a prime, 
and so it breaks out of that second loop without completing it, which 
means the else block isn't executed.

If it can't find anything that i is divisible by, then that inside for 
loop finishes without breaking, we know that i is a prime number, and 
the "else" clause is executed.

range(2,2) is is an empty list, so the loops ends uneventfully without 
doing anything and the else clause is executed.

I'm not an expert, and this seems to me to be what's happening there.

Simón

kinuthia muchane wrote:
> 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...
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list