6. is_prime - Indentation Problem



Hey guys, i'm new to all of this world so maybe that's a stupid question... but i don't understand why the indentation before the "else" under the "for n in range" is incorrect ???

When i delete the indentation everything works fine, but when i keep it it says that is_prime(3) return "None".

Can anyone try explain me why is it happening?
Thanks :slight_smile:

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


first your for loop:

for n in range(2,x-1):

why x-1? range() won't include x, so no need to do minus one again.

then it should work fine for three, but not for nine.

Why is this? because a for loop ends the moment a return keyword is reached. which happens in your first run of your for loop, because either if is true, or else will run, either way, a return keyword is reached in the first run of the loop

But you only want to return True after the for loop has finished, change the indent of else so it has the same indention level as the for loop


Got it - Thank you so much !