6. is_prime


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#


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


I don't see what's wrong.


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


#2

range doesn't includes its stop value, so why subtract one?

a function ends the moment a return keyword is reached, if a return keyword is reached in a loop, the loop will break

so your loop breaks in its first iteration, is this desired? No

You only want to return True after the loop has finished running


#3

So should i remove the return False statement in the for loop?


#4

i have tried this but it still doesnt work:

def is_prime(x):

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

#5

the return False is fine.

which means return True should be outside/after the for loop


#6

Thanks so much! I tried this and it worked, i finally understand it :slight_smile:

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

#8