Is_prime Help


#1

I'm getting the error "Oops, try again. Your function fails on is_prime(3). It returns None when it should return True." and I can't figure out how to make my code work properly. Can someone please help me?
Thanks in advance!


#2

The if statement should not have an else branch. Move the return to the end of the function, outside of the loop.


#3

Thank you, it worked! I don't really understand why though, could you explain that?


#4

In the trial division, only divisible numbers are rejected. When the loop finishes, that means the value entered was not rejected, so it must be prime.

The final return line lets you remove this line, as well...

if x == 2: return True

The loop will not run (when x is 2) because the range is 2..1 which it not iterable. That means 2 falls to the last line, as well.

It's okay if you write, range(2, x).


#5

So "return" just causes a break and the last return line is not processed.. and the functions directly end with the first return!?
I woke up to this just now with your reply, thanks a lot..


#6

Anytime return is encountered the function ceases immediately and flow is handed back to the caller, along with any possible return value. False in this case, if a number is divisible, otherwise True when the last line is reached.


#7

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