AttackOnNunu

Once more into the fray


  • 홈

  • About

  • 태그

  • 카테고리

  • 아카이브

  • 검색

(Hexo_NexT_Theme) Hexo SEO - 검색 엔진 최적화

작성일 2019-07-17 In BLOG 🗂 , HEXO-NEXT-THEME 댓글:

지금 이 순간에도 전세계적으로 수 많은 웹사이트, 웹페이지가 생성되기 때문에 그 중 나의 블로그를 혼자서 다른 사람들에게 노출시키는 것은 매우 어렵습니다.
사람들이 많이 찾는 곳, 즉 트래픽이 많이 몰리는 곳에 위치해야 사람들이 스쳐지나가기라도 하지 않을까요?
그렇다면 사람들이 무언가를 검색하고자 할때, 주로 어디를 찾을까요?
한국의 경우 네이버, 대부분의 해외에서는 구글을 가장 먼저 떠올릴 것입니다.


SEO(Search Engine Optimization)

SEO 즉, 검색엔진 최적화란 무엇인지 왜 중요한지에 대해 간단히 알아보겠습니다.

What is SEO

검색엔진 최적화 란, 검색엔진이 자료를 수집하고 순위를 매기는 방식 및 알고리즘에 맞게 웹 페이지를 구성하여 검색 결과 상위에 나올 수 있도록 하는 작업을 말합니다.

검색엔진 알고리즘은 사이트 회사의 핵심 보안 사항으로 정확하게 알 수 있는 방법이 없다고 합니다. 즉, 구글과 네이버의 검색엔진 알고리즘이 다르기 때문에 우선순위나 배치가 다른 기준을 적용합니다. 다만 사람들이 오랫동안 검색엔진을 연구한 결과들로 최적화에 대한 다양한 방법론이 소개되고 있을 뿐입니다.

Why SEO

Ads vs SEO 검색광고(Ads)를 사용한다면 검색엔진의 상단에 노출되어 상대적으로 유리하지만 사용자가 광고를 클릭할 때마다 비용이 발생합니다.

개인적으로 소소하게 웹페이지를 운영하는 저희에게는 부담이되는 것은 사실입니다.

반면 SEO, 검색엔진 최적화를 통해 비용을 들이지 않고 자연스럽게 검색엔진 사용자들을 사이트로 접근하게 유도할 수 있습니다.
물론 검색광고에 비해 즉각적인 피드백 없이 긴 시간의 기다림이 필요할 수도 있습니다. (꾸준히 관리하다보면 언젠가는 찾는 사람이 많아 지겠죠!)


제가 사용하는 Hexo에도 SEO와 관련된 플러그인이 많이 있습니다.
제 블로그에 적용시킨 플러그인들을 소개시켜 드리겠습니다.

Hexo-Plugin

제가 사용하는 Hexo-NexT-Theme 에는 기본적인 SEO 설정을 간편하게 해주는 기능을 제공하고 있습니다.
자세한 설명은 https://theme-next.org/docs/theme-settings/seo 에서 확인할 수 있습니다

theme config file 즉, 테마가 설치된 경로의 `_config.yml` 에서 SEO 를 검색하면 보실 수 있습니다.

자동으로 표준 링크를 생성해주는 canonical, 검색엔진 최적화를 위한 seo 기능을 활성화 했습니다.
그리고 블로그의 포스트들에 있는 외부 링크들이 크롤러에 의해 수집되지 않도록 (nofollow 속성과 비슷) exturl 기능도 활성화 했습니다.

구글의 웹마스터(webmaster)를 사용했지만 이미지에서는 verification key 값은 지웠습니다.
아래는 구글 검색엔진의 원활한 크롤링을 위해 추가로 설치한 RSS, sitemap, robotstxt 설치방법 입니다.

hexo-generator-feed

npm (Node Package Manager) 으로 편하게 설치할 수 있습니다.

설치

npm install hexo-generator-feed --save

사용

site config file인 `_config.yml` 에 파일을 아래 내용을 추가합니다.

피드의 종류를 정할 수 있는데 만약 네이터 웹마스터툴을 사용하실 계획이라면 default 인 Atom 말고 RSS2를 권장합니다.

feed:
type: rss2 #피드의 종류(atom/rss2)
path: rss2.xml #피드가 생성될 경로
limit: 20 #최신 포스트의 개수(0 또는 false 설정시 모든 포스트)

hexo-generator-seo-friendly-sitemap

설치

npm install hexo-generator-seo-friendly-sitemap --save

사용
똑같이 site config file인 _config.yml 에 파일을 아래 내용을 추가합니다.

sitemap:
path: sitemap.xml #생성될 경로
tag: false #sitemap에 tag 포함 여부
category: false #sitemap에 category 포함 여부

hexo-generator-robotstxt

설치

npm install hexo-generator-robotstxt --save

사용
똑같이 site config file인 _config.yml 에 파일을 아래 내용을 추가합니다.

robotstxt:
useragent: "\*"
allow: - /
sitemap:



Sign up for Google Search console

블로그의 주소를 입력하고 넘어갑니다

HTML태그의 content 안의 내용을 앞서 설명한 _config.yml 파일 안의 google_site_verification 옆에 붙여 넣습니다

이제 터미널에서 generate 하고 deploy 해주시면 됩니다

hexo g -d

RSS와 sitemap이 등록되 있는 것을 확인할 수 있습니다



Reference

Hexo SEO - 하루 만에 검색 엔진 최적화 시키기

(파이썬) 03 Booleans and Conditionals

작성일 2019-07-17 In LANGUAGE 🚀 , PYTHON , KAGGLE 댓글:

Reference

  • Kaggle 홈페이지 - Kaggle
  • 5강 ‘Booleans and Conditionals’ - Python Micro-Course Home Page


불리언(Booleans)

파이썬에는 True와 False 중 하나의 값을 가지는 bool 타입의 변수가 있습니다.

  • CODE
  • CODE
x = True
print(x)
print(type(x))
True
<class 'bool'>

보통 코드에 True나 False 값을 바로 넣기보다 불리언 연산자들(boolean operators) 를 통해 boolean 값을 얻습니다. 이 연산자들은 질문에 대한 참/거짓을 알려줍니다. 아래 표와 예제들을 통해 이 연산자들을 알아보겠습니다.

비교 연산자들(Comparison Operations)

Operation Description Operation Description
a == b a equal to b a != b a not equal to b
a < b a less than b a > b a greater than b
a <= b a less than or equal to b a >= b a greater than or equal to b
def can_run_for_president(age):
"""Can someone of the given age run for president in the US?""" # 미국 헌법에는 35세 이상이여야 한다고 명시되어 있습니다"
return age >= 35

print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))
Can a 19-year-old run for president? False
Can a 45-year-old run for president? True

비교 연산자는 조금 영리한거 같지만…

3.0 == 3
True

꼭 그런거 같진 않습니다…

'3' == 3
False

비교 연산자들이 앞서 보았던 산술 연산자들(arithmetic operators)과 더해지면 무한한 범위의 수학적 테스트들을 표현하는게 가능합니다.

  • CODE
  • OUTPUT

예를 들어, 2 로 나눈 나머지가 1 인지 확인하여 숫자가 홀수 인지를 검사할 수 있습니다.

def is_odd(n):
return (n % 2) == 1
print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))
Is 100 odd? Fasle
Is -1 odd? True
비교 연산자를 사용할 때 `=` 대신 `==` 을 사용한다는 것을 기억하십시오. 만약 `n == 2` 라고 적는 다면 n의 값을 묻는 것이고, `n = 2` 라고 적으면 n에 할당된 값을 변경하는 것입니다.

불리언 값 연산(Combining Boolean Values)

파이썬은 보통의 “and”, “or”과 “not” 개념을 사용하여 boolean 값들을 연산하는 기능을 제공합니다. 사실 boolean 관련 파이썬 연산자들은 저게 전부입니다: and, or, not

이것으로 우리는 can_run_for_president 함수를 조금 더 정확하게 만들 수 있습니다.

def can_run_for_president(age, is_natural_born_citizen):
"""Can someone of the given age and citizenship status run for president in the US?""" # 미국 헌법에는 미국에서 태어난 시민이고 35세 이상이여야 한다고 명시되어 있습니다"
return is_natural_born_citizen and (age >= 35)

print(can_run_for_president(19, True))
print(can_run_for_president(55, False))
print(can_run_for_president(55, True))
False
False
True

간단하게, 아래 표현식의 결과를 예상할 수 있나요?

  • CODE
  • ANSWER
True or True and False
True

파이썬에는 위와 같은 표현식에서 우선순위 규칙(precedence rule)에 따라 연산의 순서를 결정합니다. 예를 들어, and 는 or 보다 우선순위에 있기 때문에 첫번째 표현식은 참(True)이 됩니다. 만약 왼쪽에서 오른쪽으로 연산했다면 True or True 를 먼저 실행한 다음(결과는 True), 그 결과를 False와 and 연산하여 최종 값인 False 를 얻었을 것입니다.

우선순위(order of precedence)를 외우려고 할 수도 있지만 괄호를 사용하는 것이 더 안전한 방법입니다. 이는 버그를 방지하는데 도움이 될 뿐만이 아니라 코드를 읽는 모든 사람이 이해하기 수월해 집니다.

예를 들어, 아래의 코드를 살펴보세요.

prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday

오늘 날씨에 …

  • 만약 우산을 가지고 있다면…
  • 혹은 만약 비가 많이 오는게 아니고 내가 후드를 가지고 있다면…
  • 아니면 비가 내리지 않고 일하는 날이 아니라면 준비되었는지 말해줍니다

위 파이썬 코드는 버그가 있을뿐만 아니라 읽기에도 힘듭니다. 괄호를 추가해서 두 가지의 문제점을 해결해 보겠습니다:

prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)
  • Single_parenthese
  • More_parenthese
  • Multiple_lines

각각 괄호로 묶어 주겠습니다.

<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">prepared_for_weather = have_umbrella <span class="keyword">or</span> (rain_level &lt; <span class="number">5</span> <span class="keyword">and</span> have_hood) <span class="keyword">or</span> <span class="keyword">not</span> (rain_level &gt; <span class="number">0</span> <span class="keyword">and</span> is_workday)</span><br></pre></td></tr></table></figure>

가독성을 높이기 위해 괄호를 더 사용해도 좋습니다

<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">prepared_for_weather = have_umbrella <span class="keyword">or</span> ((rain_level &lt; <span class="number">5</span>) <span class="keyword">and</span> have_hood) <span class="keyword">or</span> (<span class="keyword">not</span> (rain_level &gt; <span class="number">0</span> <span class="keyword">and</span> is_workday))</span><br></pre></td></tr></table></figure>

혹은 위에서 언급한 3가지 조건을 강조하기 위해 여러 줄로 작성해도 됩니다.

<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">prepared_for_weather = (</span><br><span class="line">  have_umbrella</span><br><span class="line">  <span class="keyword">or</span> ((rain_level &lt; <span class="number">5</span>) <span class="keyword">and</span> have_hood)</span><br><span class="line">  <span class="keyword">or</span> (<span class="keyword">not</span> (rain_level &gt; <span class="number">0</span> <span class="keyword">and</span> is_workday))</span><br><span class="line">)</span><br></pre></td></tr></table></figure>




조건문(Conditionals)

불리언(boolean)은 그 자체만으로도 매우 유용하지만 if, elif, else 키워드를 사용하는 조건문과 함께 사용되면 진가를 발휘됩니다.

조건문 혹은, if-then 문을 사용하면 프로그래머는 일정 불리언 조건(참/거짓 조건)에 따라 특정 코드를 실행할 수 있게 됩니다. 파이썬 조건문의 기본 예제는 다음과 같습니다.

def inspect(x):
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is unlike anything I've ever seen...")

inspect(0)
inspect(-15)
0 is zero
-15 is negative

파이썬의 if와 else는 다른 언어에서 주로 사용하는 것과 같습니다; elif 는 조금 독특한 키워드로 else if 를 축약한 단어입니다. 조건문에서 elif 와 else 는 선택사항입니다. elif 는 얼마든지 추가하고 싶은만큼 추가하실 수 있습니다.

콜론(:)과 공백을 사용하여 별도의 코드 블록을 나타내는 것을 기억하시길 바랍니다. 이는 함수를 정의 할 때와 유사합니다; 함수의 헤더는 :로 끝나고 다음 줄은 4칸 들여 쓰기됩니다. 모든 들여쓰기 된 줄들은 다음 들여쓰기가 안된 줄을 만날 때까지 하나의 함수에 속하게 됩니다.

def f(x):
if x > 0:
print("Only printed when x is positive; x =", x)
print("Also only printed when x is positive; x =", x)
print("Always printed, regardless of x's value; x =", x)

f(1)
f(0)
Only printed when x is positive; x = 1
Also only printed when x is positive; x = 1
Always printed, regardless of x's value; x = 1
Always printed, regardless of x's value; x = 0

불리언 변환(Boolean conversion)

우리는 앞서 int 형으로 바꿔주는 int() 와, float 형으로 바꾸는 float() 봤기 때문에, bool 형으로 바꿔주는 bool() 이라는 함수가 있다는 것이 별로 놀랍지 않습니다.

print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)
# are "falsey" and the rest are "truthy"
True
False
True
False

boolean이 예상되는 조건문에서 non-boolean 객체를 사용할 수 있습니다. 파이썬은 암시적으로 그에 상응하는 boolean 값으로 처리 할 것입니다 :

if 0:
print(0)
elif "spam":
print("spam")
spam

조건식(일명 ‘삼항연산(ternary)’)

어떤 조건에 따라 두 개의 값 중 하나를 변수의 값으로 설정하는 것은 매우 흔한 패턴입니다.

def quiz_message(grade):
if grade < 50:
outcome = 'failed'
else:
outcome = 'passed'
print('You', outcome, 'the quiz with a grade of', grade)

quiz_message(80)
You passed the quiz with a grade of 80

파이썬에는 이러한 경우에 문장을 단순화 시킬 수 있는 단일 라인 조건식 구문(syntax)을 지원합니다.

def quiz_message(grade):
outcome = 'failed' if grade < 50 else 'passed'
print('You', outcome, 'the quiz with a grade of', grade)

quiz_message(45)
You failed the quiz with a grade of 45

보시면 다른 언어에 있는 삼항 연산자와 비슷하다는 것을 알 수 있습니다. 예를 들어, javascript에서 라면 우리는 위의 표현을 var outcome = grade <50? 'failed': 'passed' 로 작성할 것입니다. (하지만 가독성 측면에서 파이썬이 더 우수하다고 생각합니다.)




연습문제(Your Turn)

booleans and conditionals -> third Python programming exercise

(파이썬) 02 Functions and Getting Help

작성일 2019-07-15 In LANGUAGE 🚀 , PYTHON , KAGGLE 댓글:

Reference

  • Kaggle 홈페이지 - Kaggle
  • 3강 ‘Functions and Getting Help’ - Python Micro-Course Home Page

개요(Intro)

앞서 print 나 abs 와 같은 함수를 사용해 보았습니다. 파이썬에는 이 외에도 수 많은 내장 함수들을 가지고 있고 자신만의 함수를 정의하여 사용할 수도 있습니다.

이번 강에서는 함수를 정의하고 사용하는 방법에 대해 배워보겠습니다.




도움말 활용(Getting Help)

만약 abs 함수의 기능이 무엇인지 잊어버렸다면 어떻게 하시겠습니까?

help()함수는 아마 파이썬 함수 중에서도 가장 중요한 함수일 것입니다. help()함수의 정확한 사용법을 알게 된다면 대부분의 다른 함수들을 이해하는 열쇠를 쥐고 있는 것과 다름 없습니다.

  • CODE
  • OUTPUT

예제,

help(round)

출력,

Help on built-in function round in module builtins:

round(...)
round(number[, ndigits]) -> number

Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.

`help()`함수는 2 가지를 보여줍니다:1. 해당 함수의 헤더 `round(number[, ndigits])`. 이 경우 `round()` 함수가 `number`로 설정한 인자를 취한다는 것을 알 수 있습니다. 또한 사용자는 선택적으로 `ndigits`로 설정된 별도의 인자를 제공 할 수 있습니다.2. 해당 함수의 기능에 대한 (영어)설명

Common pitfall(흔히하는 실수)

함수(function)를 찾을 때 함수의 이름을 전달해야하며 함수를 호출 한 결과는 전달하지 말아야합니다.

  • CODE
  • OUTPUT

What happens if we invoke help on a call to the function abs()?

결과를 확인해 보세요->

help(round(-2.01))

원하던 결과가 아님

Help on int object:

class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| self != 0
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| default object formatter
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(...)
| Returns size in memory, in bytes
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| bit_length(...)
| int.bit_length() -> int
|
| Number of bits necessary to represent self in binary.
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| from_bytes(...) from builtins.type
| int.from_bytes(bytes, byteorder, *, signed=False) -> int
|
| Return the integer represented by the given array of bytes.
|
| The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
|
| The byteorder argument determines the byte order used to represent the
| integer. If byteorder is 'big', the most significant byte is at the
| beginning of the byte array. If byteorder is 'little', the most
| significant byte is at the end of the byte array. To request the native
| byte order of the host system, use `sys.byteorder' as the byte order value.
|
| The signed keyword-only argument indicates whether two's complement is
| used to represent the integer.
|
| to_bytes(...)
| int.to_bytes(length, byteorder, *, signed=False) -> bytes
|
| Return an array of bytes representing an integer.
|
| The integer is represented using length bytes. An OverflowError is
| raised if the integer is not representable with the given number of
| bytes.
|
| The byteorder argument determines the byte order used to represent the
| integer. If byteorder is 'big', the most significant byte is at the
| beginning of the byte array. If byteorder is 'little', the most
| significant byte is at the end of the byte array. To request the native
| byte order of the host system, use `sys.byteorder' as the byte order value.
|
| The signed keyword-only argument determines whether two's complement is
| used to represent the integer. If signed is False and a negative integer
| is given, an OverflowError is raised.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number


\*

파이썬 내부에서는 다음과 같이 표현식을 해석합니다. 먼저 round(-2.01) 값을 계산한 다음 해당 표현식의 결과에 대한 도움말(help)을 제공합니다.

(도움말(OUTPUT)을 보면 integer 에 대해 참 많은 설명이 있습니다. 나중에 파이썬에서 객체, 메소드, 속성에 관해 배우고나면 위의 방대한 도움말 출력이 더 잘 이해가 될 것입니다.)

round는 짧은 docstring을 가진 매우 간단한 함수입니다. help는 print 함수와 같이 보다 복잡하고 다양한 기능을 가진 함수를 다룰 때 더 많은 도움을 줍니다. 다음 출력 결과가 지금은 이해가지 않아도 걱정하지 마세요… 지금은 이 도움말에서 새로운 점이 있는지 확인만 하셔도 됩니다.

help(print)
Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

뭔가 발견하셨나요? 예를 들어 print가 sep라는 인자를 취할 수 있다는 것을 알 수 있습니다. 그리고 설명을 통해 인자들 사이에 넣는 문자열이라는 것을 알 수 있습니다.

함수정의(Defining functions)

내장 함수(builtin function)는 훌륭하지만, 상황에 따라 나만의 함수가 필요하기도 합니다. 아래의 간단한 예제를 살펴보겠습니다.

def least_difference(a, b, c):
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)

이 코드는 a, b와 c라는 세 개의 매개변수를 취하는 least_difference라는 함수를 생성합니다.

함수는 def 라는 키워드의 헤더로 시작합니다. : 다음에 들여쓰기 된 코드 블록(즉, 2번째 줄부터)은 함수가 호출 될 때 실행됩니다.

return은 함수와 관련된 또다른 고유한 키워드입니다. 파이썬에서 return 문을 만나면 함수를 즉시 종료하고 (return의)오른쪽에있는 값을 전달합니다.

least_difference()가 어떤 기능을 하는지 아시겠나요? 확실하지 않은 경우 몇 가지 예를 통해 언제든지 시도해 볼 수 있습니다.

  • EXAMPLE 1
  • EXAMPLE 2

함수에 인자를 넣어서 확인해 볼 수 있습니다

print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
)
9 0 1

혹은 help() 함수를 사용해서 설명을 읽어볼 수 있습니다

help(least_difference)
Help on function least_difference in module **main**:

least_difference(a, b, c)

아쉽게도 파이썬은 제가 작성한 코드를 읽고 설명을 작성할 만큼 똑똑하지 못한 것을 볼 수 있습니다.하지만 우리는 함수를 작성하며 이 함수에 대한 설명을 추가할 수 있습니다. 이를 docstring 이라고 합니다

Docstring

  • CODE
  • OUTPUT
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.

>>> least_difference(1, 5, -5)
4
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)


docstring은 함수 바로 뒤에 삼중 따옴표 `"""`로 묶인 문자열(여러 줄로 작성 가능)입니다. 이 함수에 대한 `help()`를 호출하면 docstring이 표시됩니다.
help(least_difference)
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Help on function least_difference in module __main__:</span><br><span class="line"></span><br><span class="line">least_difference(a, b, c)</span><br><span class="line">  Return the smallest difference between any two numbers</span><br><span class="line">  among a, b and c.</span><br><span class="line"></span><br><span class="line">  &gt;&gt;&gt; least_difference(1, 5, -5)</span><br><span class="line">  4</span><br></pre></td></tr></table></figure>

참고
docstring의 마지막 두 줄은 예제 함수의 호출과 결과입니다.
(>>>는 파이썬 대화형 셸(interactive shells)에서 사용되는 명령 프롬프트에 대한 참조입니다.) 파이썬은 예제 호출을 실행하지 않습니다.
이는 독자의 이익을 위해서입니다. 함수의 docstring에 보편적으로 하나 이상의 예제 호출을 포함하지 않지만, 설명을 읽는 사람이 함수의 기능을 이해하도록 돕는 데 매우 효과적 일 수 있습니다.
실제 예를 보려면 numpy 함수 np.eye에 대한 설명서를 참조하십시오.

훌륭한 프로그래머들은 docstring을 사용합니다. 만약 그 코드를 사용하고 버릴 계획이 아니라면 말이죠(이는 드문 경우입니다).
여러분도 docstring을 작성하는 습관을 들이시길 바랍니다.

반환값이 없는 함수들(Functions that don’t return)

만약 우리가 작성한 함수(function)에 return 키워드를 작성하지 않으면 어떻게 될까요?

  • CODE
  • OUTPUT
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
min(diff1, diff2, diff3)

print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7),
)

None None None

파이썬은 그러한 함수 정의를 허용합니다. 그 함수들의 호출 한 결과는 None이라는 특별한 값을 가집니다. (이는 다른 언어의 “null”개념과 유사합니다.)

return 문이 없으면 least_difference 는 완전히 무의미해 보이지만 이 함수를 통해 아무 것도 반환하지 않고 유용한 작업을 수행 할 수 있습니다.
우리는 이러한 함수를 2개나 봤습니다: print()와 help()함수는 아무 것도 반환하지 않았습니다.
우리는 함수들의 부작용(side effect - 화면에 텍스트를 넣는 것)을 위해서만 호출합니다. 유용한 부작용의 다른 예는 파일에 쓰거나 입력을 수정하는 것을 포함합니다.

  • CODE
  • OUTPUT
mystery = print()
print(mystery)
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">None</span><br><span class="line">      </span><br></pre></td></tr></table></figure>

기본 매개변수(Default arguments)

help(print) 를 호출하면 print 함수에는 몇 가지의 선택적 매개변수들(optinal arguments)이 있는 것을 볼 수 있습니다.
예를 들어, 출력하고자 하는 값들 사이에 우리가 원하는 특별한 sep 값을 지정할 수 있습니다.

print(1, 2, 3, sep=' < ')
1 < 2 < 3

만약 특정한 값을 명시하지 않으면, sep 에는 기본값인 ' '(공백) 이 들어갑니다.

print(1, 2, 3)
1 2 3

우리가 정의한 함수에 선택적 매개변수를 기본값으로 추가하는 것은 꽤 간단합니다.

def greet(who="Colin"):
print("Hello,", who)

greet()
greet(who="Kaggle")

# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)

greet("world")
Hello, colin
Hello, Kaggle
Hello, world

함수들에 적용되는 함수들(Functions Applied to Functions)

처음에는 매우 추상적이라고 느낄 수 있지만 매우 매우 유용한 기술이 있습니다.
함수는 다른 함수의 매개변수로 사용될 수 있습니다. 몇 가지 예를 들어 보면 다음과 같습니다.

  • EXAMPLE 1
  • EXAMPLE 2
  • CODE
  • OUTPUT
<div class="note primary">
        <figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mult_by_five</span><span class="params">(x)</span>:</span></span><br><span class="line">  <span class="keyword">return</span> <span class="number">5</span> * x</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">call</span><span class="params">(fn, arg)</span>:</span></span><br><span class="line">  <span class="string">"""Call fn on arg"""</span></span><br><span class="line">  <span class="keyword">return</span> fn(arg)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">squared_call</span><span class="params">(fn, arg)</span>:</span></span><br><span class="line">  <span class="string">"""Call fn on the result of calling fn on arg"""</span></span><br><span class="line">  <span class="keyword">return</span> fn(fn(arg))</span><br><span class="line"></span><br><span class="line">print(</span><br><span class="line">  call(mult_by_five, <span class="number">1</span>),</span><br><span class="line">  squared_call(mult_by_five, <span class="number">1</span>),</span><br><span class="line">  sep=<span class="string">'\n'</span>, <span class="comment"># '\n' is the newline character - it starts a new line</span></span><br><span class="line">)</span><br><span class="line">      </span><br></pre></td></tr></table></figure>
      </div>
5
25
다른 함수에서 작동하는 함수를 "Higher order function"이라고합니다.아마 지금 당장은 잘 사용하지 않으시겠지만 파이썬에 내장된 매우 유용한 고차 함수들(higher order function)이 있습니다.
  • CODE
  • OUTPUT

max 함수에 대한 흥미로운 예제입니다,

<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mod_5</span><span class="params">(x)</span>:</span></span><br><span class="line">  <span class="string">"""Return the remainder of x after dividing by 5"""</span></span><br><span class="line">  <span class="keyword">return</span> x % <span class="number">5</span></span><br><span class="line"></span><br><span class="line">print(</span><br><span class="line">  <span class="string">'Which number is biggest?'</span>,</span><br><span class="line">  max(<span class="number">100</span>, <span class="number">51</span>, <span class="number">14</span>),</span><br><span class="line">  <span class="string">'Which number is the biggest modulo 5?'</span>,</span><br><span class="line">  max(<span class="number">100</span>, <span class="number">51</span>, <span class="number">14</span>, key=mod_5),</span><br><span class="line">  sep=<span class="string">'\n'</span>,</span><br><span class="line">)</span><br><span class="line">    </span><br></pre></td></tr></table></figure>
Which number is biggest?
100
Which number is the biggest modulo 5?
14
기본적으로 `max` 함수는 가장 큰 인수를 반환합니다.그러나 선택적 `key` 인자를 사용하여 함수를 전달하면 `key(x)` (일명 'argmax')를 최대화하는 인자 `x`를 반환합니다.




연습문제(Your Turn)

함수(Function)는 파이썬 프로그래밍의 새로운 세상을 열어줍니다. second Python programming exercise

1…282930…33
NUNU

NUNU

개인적으로 공부하면서 정리한 내용들을 블로그에 남기고 있습니다.
99 포스트
18 카테고리
53 태그
RSS
Creative Commons
© 2021 NUNU
Powered by Hexo v3.9.0
|
Theme – NexT.Mist v7.2.0