빅데이터 전문가 되기
사용자 정의 함수 본문
docstring
: 모듈, 함수, 클래스 또는 메소드 정의의 첫 번째 명령문으로 발생하는 문자열 리터럴
def hello():
"""이 함수는 'Hello World!'를 출력한다!"""
print("Hello World!")
hello()
> Hello World!
def hello():
"""이 함수는 'Hello World!'를 출력한다!"""
print("Hello World!")
> Help on function hello in module __main__:
hello()
이 함수는 'Hello World!'를 출력한다!
함수 설명을 담은 docstring을 작성하여, hello() 함수를 문서화하였습니다.
- 심화된 사용자 정의 함수 만들기
# 숫자가 나오게 되면 에러가 뜨도록 만듦.
# default값이 None(함수가 반환하는 값이 없다.)
# python pep8 참고!
def hello(name: str) -> None:
if not isinstance(name, str):
raise TypeError("Name Must be a string!")
print(f"안녕!, {name}")
hello("Lee")
hello(123)
> 안녕!, Lee
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-5e39de1ca814> in <cell line: 7>()
5
6 hello("Lee")
----> 7 hello(123)
<ipython-input-15-5e39de1ca814> in hello(name)
1 def hello(name: str) -> None:
2 if not isinstance(name, str):
----> 3 raise TypeError("Name Must be a string!")
4 print(f"안녕!, {name}")
5
TypeError: Name Must be a string!
# 원소의 갯수가 상관없는 덧셈 함수
def add(*args):
print(args, type(args))
add(1,2,3,4,5)
> (1, 2, 3, 4, 5) <class 'tuple'>
*args
- tuple 형태
- 정해지지 않은 수의 (일반) 파라미터를 받음.
def add(*args):
addition = 0
for number in args:
addition += number
return addition
print(add(1,2))
print(add(1,2,3))
print(add(1,2,3,4))
> 3
6
10
**kwargs
- dictionary 형태
- 정해지지 않은 수의 (키워드) 파라미터를 받음.
- 머신러닝 클래스, 하이퍼 파라미터 튜닝할 때 사용.
- (입력값이 dictionary를 기본 값으로 받음.)
def temp(**kwargs): # **kwargs : dictionary 형태로 받음.
for key, value in kwargs.items():
print(key, value)
temp(name="hanyoung", age=30, city="Busan")
> name hanyoung
age 30
city Busan
'Python' 카테고리의 다른 글
Selenium 라이브러리 (0) | 2023.04.18 |
---|---|
라이브러리 자료모음 (0) | 2023.04.14 |
List 요소 삭제 (0) | 2023.04.13 |
시퀀스 자료형(sequence types) (1) | 2023.04.13 |
Immutable 과 Mutable (0) | 2023.04.13 |
Comments