원문 : http://learnpythonthehardway.org/book/ex25.html
함수 사용법에 대해 더 알아보자 (ex25.py)
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
코드를 읽어보자
break_words 함수는 문자열을 입력받아서 공백("' '") 단위로 분리하고 분리된 배열을 돌려주는 함수 이구나
sort_words 함수는 배열을 입력받아서 정렬하고 이를 돌려주는 함수 이구나
print_first_word 함수는 문자 배열에서 맨 앞자리를 뽑아내(pop) 인쇄하는 함수 이구나
print_last_word 함수는 문자 배열에서 맨 뒷자리를 뽑아내(pop) 인쇄하는 함수 이구나
sort_sentence 함수는 문자열을 입력받아 공백 단위로 분리(break_words)한 다음에 정렬해(sort_words)서 돌려주는 함수 이구나
print_first_and_last 함수는 문자열을 입력받아 공백 단위로 분리(break_words)한 다음에 맨 앞자리와 뒷 자리를 뽑아내 인쇄하는(print_first_word, print_last_word) 함수 이구나
print_first_and_last_sorted 함수는 문자열을 입력받아 공백 단위로 분리한 다음에 정렬하고(sort_sentence) 맨 앞자리와 뒷 자리를 뽑아내 인쇄하는(print_first_word, print_last_word) 함수 이구나
그런데....
문자열을 다루는 함수들을 쭉 만들어놓고 실제로 사용하는 코드는 하나도 없네?
일단 실행해 보자
아무 일도 안일어난다.
그럴 수 밖에....
그러면 미리 작성된 함수들을 사용 해 보자.
일단 python shell 을 실행시킨다. (python.exe)
이런 화면이 나오고 ">>>" 커서가 보이면 python shell 이 실행된 것이다.
이제 미리 작성된 함수들을 사용해 보자
알 수 있는 내용
1. shell 을 이용해서 결과를 바로바로 확인 해 볼 수 있다.
2. 미리 작성된 소스를 사용하기 위해서는 "import 파일명"
3. "파일명.함수명" 으로 다른 파일에 있는 함수를 사용 할 수 있다.
4. 문장을 구분자로 분리(배열) 할 때는 "split('구분자')" 함수를 사용한다.
5. 배열에서 값을 뽑아낼 때는 "pop(위치)" 함수를 사용한다. (위치는 0 부터 시작. 맨 뒤는 -1)
'Python > Python 어렵게 배우기' 카테고리의 다른 글
| Python 어렵게 배우기 - Exercise 27: Memorizing Logic (0) | 2013.12.18 |
|---|---|
| Python 어렵게 배우기 - Exercise 26: Congratulations, Take a Test! (0) | 2013.12.18 |
| Python 어렵게 배우기 - Exercise 24: More Practice (0) | 2013.12.17 |
| Python 어렵게 배우기 - Exercise 23: Read Some Code (0) | 2013.12.16 |
| Python 어렵게 배우기 - Exercise 22: What Do You Know So Far? (0) | 2013.12.16 |