6. is_prime - Could someone please clarify me on what i'm doing wrong?


#1



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


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


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


#2

by default a function returns None, so the fact that this happens indicate no return keyword is reached. Which return keyword did you think it would reach?

i wrote an extensive explanation yesterday, you can read it here:


#3

How do i ensure that "True" is only returned after the loop has finished running without being broken by "return False".
Thanks for your response.


#4

by placing return True outside the loop. There are two options, use for/else, then else will run when loop condition becomes false (this means the loop has finishes running, this won't happen if false is returned), or get rid of else altogether and just return True after the loop has finished running


#5

Let me give it a try. Will buzz you if i run into further error or if i get confused. Thanks a lot. Really appreciate.


#6

Worked like magic. Thanks again.

But i have a question
Does this line "well, range() doesn't includes its stop value, so you don't need to subtract one of x for range stop value" to all cases, or to just this case?


#7

Does this line "well, range() doesn't includes its stop value, so you don't need to subtract one of x for range stop value" apply to all cases, or to just this case?


#8

well, range never includes its stop value, so range(5) would give [0,1,2,3,4]. For your is prime program goes that you don't need to subtract one of x.


#9

Thanks for assisting :+1:


#10

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