Is prime. What's wrong?


#1



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


Fails on is_prime(5). Returns None when it should return True


It looks like the other corrected examples in the Q&A to me.


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


#2

    else:
        return True

why do you have an else here? now for x=5 the elif is true, so else won't run


#3

Ok, I got it, thanks. I needed to indent the final else statement. Still this looks strange to me, it really seems like it should be indented the same as that last if statement. Is this a for/else loop or is this just how an if/else loop looks within a for loop. Sorry, I'm not sure how to show my indents in a reply.

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

#4

you still think it should be:

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

?

lets say x=9, then the first value tested by the loop is 2:

9 % 2 == 0

which evaluate to False, now else will run. So now, true is returned. But a return keyword means the function will end. Given we are in a loop, the loop will break so the function can end

Now are function doesn't work correctly anymore

if we use for/else, else will run when loop condition becomes False.

This only happens when the if condition is never true (if it was, a return keyword would be reached, the function would end)

So, for/else is perfect for our intended solution


#5

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