[Tutor] Prime Numbers
Joel Goldstick
joel.goldstick at gmail.com
Sun Dec 15 18:06:44 CET 2013
On Sun, Dec 15, 2013 at 11:54 AM, Rafael Knuth <rafael.knuth at gmail.com>wrote:
> Hej,
>
> I stumbled upon this program here (Python 3.3.0) and I don't quite
> understand how the for loop plays with the return True statement:
>
> def is_prime(number):
> for element in range(2, number):
> if number % element == 0:
> return False
> return True
>
> Now, I would expect the following in case I call the function with the
> variable 3:
>
> number = 3
> for element in range(2, 3):
> 3 % 2 != 0:
> Loop ends and program returns True.
>
> Let's do the same with the variable 9:
>
> number = 9
> for element in range(2,9):
> 3 % 2 != 0:
> My assumption is that the program should end the loop after the first
> iteration again and it then should return True.
>
3 % 2 isn't 0, so it increments element to 4. $ % 2 is 0 so it returns
false
The loop goes thru each number until it finds a factor ( == 0 is true). If
it doesn't find a factor of the number after checking all numbers up to the
number, it continues to the return true statement
>
> But instead, the program returns False (correctly for obvious reasons
> because 9 is not a prime number). Can anyone help me understand what
> error in reasoning I am making here?
>
> Thanks!
>
> All the best,
>
> Raf
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
--
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131215/b580caa7/attachment.html>
More information about the Tutor
mailing list