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

After playing with my code for quite some time, I figured out that else in last line is not to be included instead return true should not be indentated for FOR loop but for my def function!(and my code works fine with that)

But anyone can explain me why is this happening?


Yea, i can explain :slightly_smiling: First, it is important to realize that a function ends a return statement is reached. What is happening? The moment return is reached, something is returned and the function (and obviously the loop in the function included) ends.

So, with this knowledge, lets look at your code. In the first run of your loop, either if is true or else gets executed. Either way, a return statement is reached, so the function ends. So, your loop ran only once. Which is a bit of a problem

Like you mentioned, putting else (or don't put else at all, just return True) outside your for loop, will make the loop run for all numbers in the range if it is a prime number, nothing gets returned all that time. Then after the for loop, return True gets reached. If the number is not a prime number, False gets returned and the function ends. This is rather efficient, because we already know the number is not a prime, so we don't have to run the rest of the numbers

Hope this helped