为什么这个缩进有效?蟒蛇

use*_*635 3 python indentation

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么最后一个else: return true与缩进一起工作.如果我输入

else:
            for i in range(2,x):
                if x % i == 0:
                    return False
                else:
                    return True
Run Code Online (Sandbox Code Playgroud)

然后def is_prime(2)返回none?为什么?

msv*_*kon 8

因为在python中,for-loop可以有一个else-clause.

如果循环正常退出,则执行此子句.如果使用该break语句退出循环,else则不会输入.

我建议你阅读官方文档,如果还不清楚,这个博客很好地总结了这个概念.