Python/Python Programming

[Python] 중첩 함수 (Nested Function)

Pydole 2018. 4. 28. 15:47

함수의 안에 다른 함수를 정의할 수 있다. 

 


 

 

1.  1 ~ 100의 값으로 구성된 리스트에서 5나 7로 나누어 지는 수를 추출

 

def func1(a):
    def func2():
        result1 = []
        for i in a:
            if i % 5 == 0:
                result1.append(i)
        return result1

    def func3():
        result2 = []
        for i in a:
            if i % 7 == 0:
                result2.append(i)

        return result2

    return sorted(func2() + func3())

print(func1([i for i in range(101) if i != 0]))
[5, 7, 10, 14, 15, 20, 21, 25, 28, 30, 35, 35, 40, 42, 45, 49, 50, 55, 56, 60, 63, 65, 70, 70, 75, 77, 80, 84, 85, 90, 91, 95, 98, 100]

 

 

 

2.  외부에서는 func2 함수와 func3 함수는 보이지 않는다.

print(func2([i for i in range(101) if i != 0]))
NameError: name 'func2' is not defined