brunch

You can make anything
by writing

C.S.Lewis

by Younggi Seo Apr 25. 2018

함수와 라이브러리 in PYTHON

Method and built-in-function in Python

이전 세션에서 다룬 파이썬의 기본적인 자료(collection of information) 개념에 이은 function 개념의 심화된 리뷰다. 일반적인 컴퓨터 언어에서의 function(수학의 함수와는 다른 별도의 정의가 필요한)과 현실세계의 행복을 연관 지은 발상을 시작으로 개념을 심화시켜 보려고 한다. 아래는 'Think Python'이라는 UoPeople 대학 교재물에서 발췌한 내용이다. 사용자가 정의해서 사용할 수 있는 새로운 function('Add new functions')의 용도에 대한 설명이다.

 


Definitions and uses


Pulling together the code fragments from the previous section, the whole program looks like this:(예제)

def print_lyrics():
    print("I'm a lumberjack, and I'm okay.")
    print("I sleep all night and I work all day.")

def repeat_lyrics():
    print_lyrics()  
    print_lyrics()

repeat_lyrics()  


This program contains two function definitions: print_lyrics and repeat_lyrics. Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not run until the function is called, and the function definition generates no output. 위의 함수 내부의 print 명령문들은 이 함수가 호출되기 전까지는 실행되지 않는데 호출되기 전에는 실행하지 않는 이 함수의 정의는 아무런 결과도 내놓지 않는다.



창가 밖으로 보이는 아이들이 뛰어노는 모습을 볼 때면 아이들은 무척이나 행복하게 보인다. 정말 그저 뛰어놀고 있는 것만으로도 행복하다. 그 아이들(객체)이 뛰어노는 것(print 명령문) 그 자체를 행복(함수)이라고 정의할 수 있지만 제삼자의 시선에서 그것을 행복이라고 정의된 단어로 불러주지(함수 호출) 않는다면 행복하다고 표현할 수 없다. 밖에서 뛰어놀던 아이들은 지금이 자신들의 삶 가운데 가장 행복한 상태인지 결코 알 수 없을 테다.


정작 뛰어노는 순간이 행복이라고 알아야 할 당사자들은 그 시간이 당연한 흐름이었다면 그것을 지나고 나서야 정말 행복한 순간이었다고 깨달을 수밖에 없는 인간의 사고영역이 프로그래밍에서의 함수의 쓰임새가 누군가에게 호출되어야지만 활용될 수 있는 형태와 비슷하게 느껴져서 잠깐 공상해봤다('삶의 비약', 2018).



As you might expect, you have to create a function before you can run it. In other words, the function definition has to run before the function gets called. As an exercise, move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get. Now move the function call back to the bottom and move the definition of print_lyrics after the definition of repeat_lyrics. What happens when you run this program?


예상했듯이 프로그래머는 함수를 먼저 만들어야 이후에 그것을 실행시킬 수 있다. 다른 말로 그 함수의 정의를 실행한 뒤에 함수는 부름을 받을 수 있다. 처음에 제시한 예제에서 이 프로그램의 마지막 행을 맨 처음으로 이동시켜라. 그래서 함수 호출을 함수를 정의하기 전에 해봐라. 프로그램을 실행시키고 어떤 에러 메시지가 발생하는지 봐라(에러 메시지 : NameError: name 'repeat_lyrics' is not defined). 이제 그 함수를 다시 맨 마지막 행에서 호출할 수 있도록 옮기고 print_lyrics 함수의 정의를 repeat_lyrics 함수 뒤로 옮겨라. 어떤가? (에러 없이 실행됨. 이것이 함수의 'hoist, 호이스트(끌어올림)'라고 함.)



Flow of execution


To ensure that a function is defined before its first use, you have to know the order statements run in, which is called the flow of execution. Execution always begins at the first statement of the program. Statements are run one at a time, in order from top to bottom. Function definitions do not alter the flow of execution of the program but remember that statements inside the function don’t run until the function is called. A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, runs the statements there, and then comes back to pick up where it left off. That sounds simple enough until you remember that one function can call another. While in the middle of one function, the program might have to run the statements in another function. Then, while running that new function, the program might have to run yet another function! Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates. In summary, when you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution.

  

실행 흐름에 대한 장문의 요약인데, boil this down to a nutshell,

statements(print, input, if, for, del과 같은 명령문)은 파이썬의 절차적(Interpreter) 프로그래밍 특성에 따라 맨 위에서 아래로 하나씩 순서대로 실행한다. 함수의 정의도(def:) 이러한 프로그램 실행의 흐름을 바꾸는 것은 아니나, 주의해야 할 점은 함수 내부에 있는 statements(함수 정의 아래에 들여 쓰기 되어있는 명령)인 경우 그 함수가 불리기 전까지는 실행하지 않는다.


함수는 고속도로에서 우회도로와 같이 중간에 샛길로 빠지는 프로그램 실행의 흐름을 가지며 함수 내부의 명령문들은 이 함수가 호출되면 실행되고 모두 실행되면 다시 함수가 호출된 자리로 되돌아온다.

  

def print_lyrics():
    print("I'm a lumberjack, and I'm okay.")
    print("I sleep all night and I work all day.")

def repeat_lyrics():     
    print_lyrics()
    print_lyrics()

repeat_lyrics()


함수의 실행 흐름은 repeat_lyrics() 함수 내부에서 print_lyrics() 함수를 두 차례 호출하고 있는 동안 print_lyrics() 함수의 statements(print 명령문)가 하나씩 실행하고 있다. print_lyrics() 함수 내부의 statements가 실행하고 있다는 것은 이 함수 외부(repeat_lyrics() 함수 내부)에서 이미 print_lyrics()가 호출되었다는 것을 알 수 있다. 그래서 개발자는 프로그램 코드를 살펴볼 때 위에서 아래로 봐야 할 경우도 있지만 맨 마지막 행의 어떤 함수가 호출되었는지 먼저 확인하면서 프로그램 실행의 흐름을 쫓는 게 나을 때도 있다.



Why functions?


It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:


• Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug. (쉽게 읽고 디버그 가능)

• Functions can make a program smaller by eliminating repetitive code. Later, if you make a change,  you only have to make it in one place. (재사용하는 코드량 줄임으로코드량 감소)

Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole. ( 번에  부분들의 함수 디버그 그리고 다시 합쳐서 실행 가능)

• Well-designed functions are often used for many programs. Once you write and debug one, you can reuse it. (잘 설계된 함수들은 많은 프로그램에서 재사용 가능)


파이썬은 인터프리터에 의해 절차적 프로그래밍의 런타임 해석을 하지만 위의 함수(function) 특성을 잘 이용하면 객체지향 언어의 장점을 활용할 수 있다는 것을 확인할 수 있다.




Reference |

Downey, A. (2016). Think Python. Sebastopol, CA: OReilly Media.

매거진의 이전글 보안을 위한 파이썬 매뉴얼
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari