본문 바로가기

Python_Beginer/Study

Python Function Basic Study - Def 함수

반응형

1. 함수(Fuction)

- 프로그램에서 반복적으로 사용될 기능을 작성한 코드

- 정의한다고 실행 되지 않고 함수를 호출해야지만 사용 가능

- 코드의 용도를 구분

- 코드를 재사용

- 실수 방지


2. 기본구조

def 함수이름(파라미터,...):
함수 수행 기능
[return 값]

- 파라미터(parameter) : 함수를 호출하는 곳에서 전달하는 값을 저장하기 위해서 선언하는 변수


3. Sample Code

- Printer Def

def say_hello(name):
print('안녕하세요. 저는 %s입니다.' % name)

- Printer Def 호출

say_hello('홍길동')

안녕하세요. 저는 홍길동입니다.


Process finished with exit code 0

- Sum Def

def add(x, y):
return x + y

- Sum Def 호출

result = add(10, 20)
print('result = %d' % result)

result = 30


Process finished with exit code 0

- Sum / Mul Def(2개 이상의 값을 리턴)

def add_and_multiply(x, y):
return x + y, x * y

- Sum / Mul Def 호출

sum, mul = add_and_multiply(10, 20)
print('sum = %d, mul = %d' % (sum, mul))

sum = 30, mul = 200


Process finished with exit code 0

- Defalut Argument(기본값)을 가진 Sum Def

def add2(x, y = 0):
return x + y

- Defalut Argument Sum Def 호출(파라미터 x에만 값 지정 / y는 Defalut Argument를 사용)

result = add2(10)
print('result = %d' % result)

result = 10


Process finished with exit code 0

- Defalut Argument Sum Def 호출(기본값 미사용)

result = add2(10, 20)
print('result = %d' % result)

result = 30


Process finished with exit code 0

- x, y에 function annotation(함수 주석)을 설정한 Def

def add(x: int, y: int) -> int:
return x + y

< x : int, y: int 주석문 발생 >

- function annotation(함수 주석) Def 호출(int + int)

print(add(2, 3))
print(add('2f', 'f2'))

5


Process finished with exit code 0

- function annotation(함수 주석) Def 호출(str + int) -> 연산자 오류 발생

print(add('2f', 3))

TypeError: can only concatenate str (not "int") to str


Process finished with exit code 1


4. 함수 실행 순서

- 파이썬 스크립터 실행 -> 함수 호출 -> 함수 실행 -> 함수지정작업 -> 함수 종료

반응형