[Tutor] Prime Numbers

Mark Lawrence breamoreboy at yahoo.co.uk
Sun Dec 15 18:51:16 CET 2013


On 15/12/2013 16:54, Rafael Knuth 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.
>
> 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

If you pass 3 into the function the code will only loop for the value 2, 
that's simply how range works.  Your friend here is the print function 
(statement in Python 2, unless you use IIRC from __future__ import 
print_function).  So try something like this and watch what happens.

def is_prime(number):
     print('is_prime number = ', number)
     for element in range(2, number):
         print('is_prime element = ', element)
         if number % element == 0:
             print('is_prime return False')
             return False
     print('is_prime return True')
     return True

for i in range(2, 10):
     is_prime(i)
     print()

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list