6. is_prime


#1

I always have problem with indent. So here is a indent error that really confuse me.
This is the answer that I have, which keep giving me error.

And the answer should be

As I highlighted, the error is the problem with indent of the last two lines.
I just don't get it. Why it is the same indent as "for n in range(2,x):"?
Shouldn't "else" go with "if x%n==0:"?
Aren't 'else', 'elif' and 'if' always go together?


#2

If you either return False or True, then you are always returning something. If you always return on the first iteration, then there can be no second iteration. So if your loop is to actually be a loop, then there has to be a scenario where a return statement is not executed each iteration. You should probably only return if you've found that it isn't a prime, otherwise just continue looping, yes?

What you have in your second screenshot is a for-else, it is not an if-else. The way you are using it, the else has no effect, you can simply remove that line and de-indent the return True statement.


#3

Bingo! Well stated question.

On the second point, given the reader is aware of it, the verbose else: is actually not such a bad thing. It helps the reader toggle flow ideas. In the code without break it is meaningless, I agree, but it doesn't hurt anything, either.