[Tutor] Else Clause In A Loop
Alan Gauld
alan.gauld at btinternet.com
Tue May 13 00:52:40 CEST 2008
"kinuthia muchane" <muchanek at gmail.com> wrote
> 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...
It doesn't find prime numbers very well.
It only finds the primes *below* the one entered.
So...
> 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)!
When number is 2 it doesnm't print anything. Which as you point
out is as you would expect since the first range() will be empty.
For number=3 the first range has one element so it enters the
second loop with an empty list so goes straight to the else
clause.
I'm not a sure what you are confused about?
The code is not very elegant or effective but it does what you
have described in your experiments.
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list