Question

here is my code:

def is_prime(x):
    if x < 2:
        return False

    else:
        for i in range(2,x):
            if x % i == 0:
                return False
        else:
            return True

print is_prime(508)

I don't understand why the last else: return true works with the indentation. If I type

else:
            for i in range(2,x):
                if x % i == 0:
                    return False
                else:
                    return True

Then def is_prime(2) returns none? why?

Was it helpful?

Solution

Because in python, a for-loop can have an else-clause.

This clause is executed if the loop exits normally. If the loop is exited by using the break statement, the else is not entered.

I suggest you read up the official doc and if it's still unclear, this blog summarizes the concept fairly well.

OTHER TIPS

for and while loops also know else clauses, not just if or try statements.

The else clause of a loop is executed when control leaves the loop, unless you have used break to abort the loop.

I must admit that this behavior puzzled me at first, as well, but it's actually quite sensible, and a useful feature (see this answer for a good example).

In the second example, the else is on the same indentation level as the if, so they both belong together. So for the first item in the loop, you will either return False or True depending on that value; i.e. the loop won’t continue.

Now in your original code, the else is on the same level as the for. So it’s a for..else which is actually a special construct:

When the items are exhausted, the suite in the else clause, if present, is executed, and the loop terminates.

So basically, the else block is executed, if the loop naturally finishes (without calling break). So in your case, it’s the same as leaving the else out:

for i in range(2,x):
    if x % i == 0:
        return False
return True

As others have said, a for loop can have an else clause. Read more in the docs

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top