Is_prime


#1



Oops, try again. Your function fails on is_prime(9). It returns True when it should return False.


Hi. I do not understand why VARIANT 1 doesn't work if i=3? It should return False because 9 or 15 % 3 == 0. In VARIANT 2 I've changed the place of else statement and it starts work correctly. I understand why Variant 2 works, but still do not understand why variant 1 does not. I ve printed the output with
for i in range (0, 16):
print i
print is_prime(i)

but still do not understand. Please, someone explain me


VARIANT 1

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    elif x > 2:
        for i in range(2, x):
            if x % i == 0:
                return False
            else:
                return True

VARIANT 2
def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    elif x > 2:
        for i in range(2, x):
            if x % i == 0:
                return False
        else:
            return True


#2

I believe what is happening is that the loop starts with 2 and compares 9 % 2 == 0 which is false so it moves to the else statement where it returns True and exits the loop because it returned a value.


#3

The if and else conditions indentation level of the for loop in both variants makes the difference.

In the first variant, you have your else condition in the for loop whereas in the second, the else condition is for the for loop itself. Indentation levels makes all the difference and consequently affects output.

I hope I helped. :slight_smile:


#4

If so, why the variant 1 returns false when x = 6?

that the point - when in the loop if first "if" statement doesn not return false it should go to else statement. or i don not understand the loop well


#5

Variant 1 returns false when x = 6 because the if condition is true, 6 % 2 == 0. Since the if condition is true it will run it's code which is to return False.


#6

Basically in the first variant the indention causes the result of the if/ else statement to be returned to the loop and NOT returned to the function is_prime. Whereas in variant two the if/else is returned directly to the function.


#7

Hi,

I decided to check the code now in a console, and seems fine, after all.

VARIANT 1 - Variant 1
VARIANT 2 - Variant 2

Thank you! :slight_smile:


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.