[Tutor] Prime Numbers

Rafael Knuth rafael.knuth at gmail.com
Sun Dec 15 17:54:10 CET 2013


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


More information about the Tutor mailing list