6. Is_Prime


#1



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


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


It seems like it should return something. I initially didn't have 2 conditioned in (if x<2 vs if x <=2: ). Seems to work with some random prime/non-prime numbers I have tested. I'm sure it is something incredibly simple but I can't locate it for the life of me. Any pointers would be awesome


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


#2

here:

if x <= 2:

are you certain this is the condition you want?

You should return True after the for loop has finished running, currently your loop would return True in the first iteration when the if condition evaluates to false.

Which means, in the first iteration of your loop, a return keyword is reached, the loop breaks, the function ends


#3

I guess I'm not really following. Wouldn't I want the loop to break if the integer was 2 or less? It wouldn't qualify as a prime number and would always be false. If the loop breaks there it should return False rather than None, correct?


#4

there are two parts here, for values less then 2 (2 not included) you want to make a if condition to return False

2 is considered a prime number

Now, the second part, your loop

You only want to return True after the loop has finished running, not in the first iteration. Currently, your loop return true or false in the first iteration, causing the loop to break and the function to end


#5

I feel silly, I misread the instructions. I think I have it right. Is this more proper? If it is thanks so much for your help!

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

#6

This looks right :slight_smile: Do you understand all of it?


#7

Yeah, it made perfect sense when I finally started looking at it correctly. Thanks again!


#8