1. Getting Help
help(round)
# Help on built-in function round in module builtins:
# round(number, ndigits=None)
# Round a number to a given precision in decimal digits.
#
# The return value is an integer if ndigits is omitted or None.
# Otherwise the return value has the same type as the number. ndigits may be negative
help() 함수는 두가지를 보여준다.
- 함수의 머릿말을 보여준다. 이 경우 round()함수는 두가지 argument를 입력받는 것을 알 수 있다. ndigits는 선택적으로 입력 가능한 argument이다.
- 함수가 어떤 역할을 하는지 간단한 설명을 제공한다
2. Defining functions
def least_difference(a, b, c) :
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
위의 코드는 세가지 arguments인 a, b, c를 입력받는 least_difference() 함수 코드이다.
함수 생성시 def 키워드로 시작해서 함수명을 작성하고 괄호 안에 어떤 argument를 받을지를 결정한다. 이후 함수의 연산을 작성하기 위해 : 를 사용하여 Code block을 만들어 준다.
return은 함수를 즉시 종료시키며 return 뒤에 나오는 코드를 출력한다.
3. Docstrings
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은 주석과 같이 특정 코드 세그먼트를 문서화하는데 사용되는 소스코드에 지정된 문자열 리터럴이다.
4. Default arguments
help(print)를 실행하게 되면, print 함수 안에 선택적인 argument가 있는 것을 알 수 있다. 예를들어 sep argument를 활성화 하게 되면, 각 문자열 안에 '<' 값을 끼워 넣어 출력해 준다.
print(1, 2, 3, sep = '<')
# result will be 1 < 2 < 3
sep argument를 활성화 하지 않게 되면 sep argument에는 ''라는 defualt 값이 들어가게 된다(일반 출력문).
print(1, 2, 3)
# result will be 1 2 3
5. Functions Applied to Functions
함수를 다른 함수의 입력 값으로 사용할 수도 있다.
def mult_by_five(x) :
return 5 * x
def call(fn, arg) :
"""Call fn on arg"""
return fn(arg)
def squared_call(fn, arg) :
"""Call fn on the resullt of calling fn on arg"""
return fn(fn(arg))
print(
call(mult_by_five, 1),
squared_call(mult_by_five, 1),
sep = '\n',
)
# result will be 5, 25
다른 함수에서 작동하는 함수를 'higher-order function'이라고 한다.
Source of the course : Kaggle Course _ Functions and Getting Help
'Course > [Kaggle] Data Science' 카테고리의 다른 글
[Python] Loops and List Comprehensions (0) | 2022.02.11 |
---|---|
[Python] Lists (0) | 2022.02.11 |
[Python] Booleans and Conditionals (0) | 2022.02.11 |
[Python] Hello, Python (0) | 2022.02.10 |
Kaggle Course Introduction (0) | 2022.02.10 |