Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this indentation work? python [duplicate]

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?

like image 518
user3454635 Avatar asked Mar 11 '26 09:03

user3454635


1 Answers

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.

like image 188
msvalkon Avatar answered Mar 13 '26 22:03

msvalkon