我应该在函数内部编写函数还是将它们全部写在全局框架中?

Sould I write a function inside of a function or write them all in the global frame?

不是一个复杂的问题,但我找不到明确的答案。

例如,如果我想找出一个数字列表中质数的个数:

def count_prime(lst):
    """lst is a list of integers"""

    def isPrime(n):
        return all(n % div != 0 for div in range(2, int(n**0.5) + 1)) if n > 1 else False

    result = 0
    for num in lst:
        if isPrime(num):
            result += 1

    return result

这看起来很简单,但是我把isPrime(n)放在了main函数里面。

与以下相比如何:

def isPrime(n):
    return all(n % div != 0 for div in range(2, int(n**0.5) + 1)) if n > 1 else False

def count_prime(lst):
    """lst is a list of integers"""

    result = 0
    for num in lst:
        if isPrime(num):
            result += 1

    return result

我的问题是:这有什么区别吗?更喜欢哪一个?

我认为这两种方法都有效。 isPrime体积很小,很容易嵌入。如果你想重用这个函数,全局定义它是有意义的。