[solved] is prime


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

I am heavily stuck here...found other solutions online, but cant understand why this code is not working? Anyone can help with explanation?

thanks


Is prime
#2

And you haven't found a explanation which explains that a function will end the moment a return keyword is reached? Even if that means it has to interrupt a loop.

I thought i wrote several of those in the last week alone. Either way, as we just determined, your loop ends in its first run, you might want to re-indent else/return True, so the whole can run before returning True (to determine if it is actually a prime number)


#3

stetim94, apologies, I'm very new to this, hence not really sure what indent is wrong? I've tried re-indenting return under else but it comes back with syntax error. Is it even possible to get solution through the code I wrote, or is it systematically wrong?

Thank you


#4

well, if you want to keep your else, you should put else at the same indent level as your for loop. You can also remove the else altogether, and put return True at the same indent level, both will have the same effect, since then True is returned after the for loop is finished


#5

Ah, stupid me...took me ages for one simple thing. Code now looks like this, and its working (finally).
stetim94, much obliged!