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

I don't understand why it fails on is_prime(0), since my condition states that if a number is smaller than 2 it should return False, that would mean numbers 0 and 1 should return False. However the errors says it returns None. And in the elif statement, what I understand is " if a number is greater than 2 then we test if it is divisible by n".
Please correct my understanding if i'm wrong. Thanks in advance!

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


The loop will iterate exactly one time. Figure why?


I didnt call the is_prime function? Not too sure...

Okay, so I only want the loop to happen for numbers 2 and above but based on my for condition, its only checking to see if the number is smaller than 2. is that why its only looping once?


The main reason is because one of the branches will be followed, no matter what, and every branch leads to a return, which ends execution.


ah ok i got it! so i have to place the return functions above the for. Thanks mtf!


Where we place the return is by design, not by any special rule. It is a point in the function where control flow kicks a result back to the caller.


def ...(x):
    if x < 2:
        return False

In the above, values less than 2 are rejected, so return False. We know that numbers less than 2 are not prime. It becomes a design constraint.


A post was split to a new topic: Your function fails on is_prime(0)


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