[Tutor] Else Clause In A Loop

kinuthia muchane muchanek at gmail.com
Wed May 14 08:47:18 CEST 2008


On Tue, 2008-05-13 at 11:09 -0400, "Simón A. Ruiz" wrote:
> kinuthia muchane wrote:
> > On Mon, 2008-05-12 at 14:08 -0400, "Simón A. Ruiz" wrote:
> >> 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.
> > 
> > This is where I am getting lost. When the variable 'number' is 3, it
> > means that in that instance the inner 'for' statement  will be 'for j in
> > range(2,3)', hmmm which means that we will be dividing each element by 2
> > in the first 'for' statement and checking whether it is true , no? But
> > 2%2 is zero, so, in my warped logic, the inner 'for' loop should break
> > and the else clause will not execute!
> 
> When i is 3, then we'll only check (2 % 3 == 0) which is False, so the 
> loop ends unbroken and runs the else clause letting us know that 3 is 
> indeed a prime number.
 
Shouldn't we be checking for (3%2 == 0) instead of (2%3 == 0)?
> 
> Never will we check (2 % 2 == 0).
> 
> When i is 2, range(2,2) returns [], so the loop ends unbroken (without 
> starting) and runs the else clause.
> 
> >> 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.
> > 
> > This is where it gets even more interesting for me. Wont 'i' in one
> > instance be 8, so at that particular moment there will be a 7 in the
> > inner 'for' loop which will be divisible by one of our 'prime' numbers
> > ie 7?! I know I am wrong but for some reason I cannot see the light! :-)
> 
> Don't worry about it, you're doing fine.
> 
> Remember, when you're most confused you're most ready to learn 
> something. :-D
> 
> Ok, so when i is 8, we check:
> is (8 % 2 == 0)? True. Break!
> So, we've broken out of the inner loop and thus ignore the else 
> statement. We know 8 is not a prime number.
> 
> Now, for a prime. When i is 7, we check:
> is (7 % 2 == 0)? False. Next!
> is (7 % 3 == 0)? False. Next!
> is (7 % 4 == 0)? False. Next!
> is (7 % 5 == 0)? False. Next!
> is (7 % 6 == 0)? False. Next!
> So, we've finished the inner loop without breaking, so we now run the 
> else clause:
> is a prime number 7
> 
> 
> Does this help at all?

It was crystal clear! Thanks Simon (I didn't know how to put the accent
mark over the 'o', though), the confusion is gone. ;) 
> 
> Hope this finds you all having a beautiful day!
> 
> Simón



More information about the Tutor mailing list