Can I write a function inside a function or write them to a global frame?

Not a difficult question, but I did not find an explicit answer.

For example, if I want to find out the number of primes in a list of numbers:

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

It looks very simple, but I put isPrime(n)inside the main function.

How does this relate to:

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

My question is: doesn't it matter? Which one is preferable?

+4
source share
1 answer

I think both approaches are valid. isPrimevery small so it can be easily inserted. If you want to reuse a function, it makes sense to define it globally.

0
source

Source: https://habr.com/ru/post/1695064/


All Articles