Is_prime


#1

def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2,x-1,1):
            if x % n == 0:
                return False
            else:
                return True

print is_prime(2)

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

Why it does so?


#2

well, lets say x=2, then we have the following condition for our loop:

range(2, 2 -1, 1)

2 - 1 is one, so then the loop condition is:

2 < 1

which is false, so the loop condition is false in its first iteration, so the loop never runs

no return keyword is reached, so the default (None) is returned by the function


#4

so how the condition should change? I don't know what to do to force function to return True for x = 2 !


#5

well, range() doesn't includes its stop value, so you don't need to subtract one of x for range stop value.

this would change the condition to:

2 < 2

which is still false, so loop still won't run

Then its important to understand what a return keyword does. By default, a function returns None at the end, if we want to return something different at then end of the function, we can use a return keyword. There is the catch, the return keyword will cause the function to end, if the return keyword is reached in a loop, the loop breaks in order for the function to be able to end

So, in other words, if a number is not a prime number, at some point in the loop, return false will be reached, which causes the loop and function to end

for a number to a prime number, the whole loop needs to run successful and then after the loop return True.

This is currently not happening, for example for x=9, the first number the loop will test is 2. 9 % 2 == 0 is false, so else runs, true is returned, loop and function ends

This is not what you want

so, true should only be returned after the loop has finished running without being broken by return False

x=2 is a bit of a special case, for the first iteration of the loop, the condition is false, but if you place return True outside the loop, true is still returned. Which is good, given 2 is a prime number


6. is_prime - Could someone please clarify me on what i'm doing wrong?
Is_prime is not working
Is_prime is not working
#7

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