함수(Functions)

함수는 def를 통해 선언한다. 함수의 이름은 변수와 마찬가지로 규칙에 따라 정해야한다.

값을 받아 함수를 처리하려면 파라미터가 있어야한다. 파라미터는 괄호( )에 들어가는 변수이다.

def print_name(name):     # 'name' => 매개변수(파라미터)
    print(f'이름은 {name}입니다')

print_name("김토끼")
print_name("이토끼")     # "김토끼", "이토끼", "박토끼" => 인자(인수)
print_name("박토끼")

파라미터는 함수를 정의하는 부분에 쓰인 변수, 인자는 함수를 실행할 때 넘겨지는 값이라고 보면 된다.

 

함수를 정의할 때 파라미터를 반드시 사용하지 않아도 된다.

def print_ex_string():
    print('예시 문자열입니다.')

print_ex_string()

 

파라미터를 두 개 이상 사용해도 된다.

def print_name_age(name, age):
    print(f'이름은 {name}이고 {age}살 입니다.')

print_name_age("김토끼", "3")

 

파라미터에 기본값을 설정하면 인자를 주지 않아도 오류가 발생하지 않는다.

def order_coffee(qty, option = 'hot'):
    print(f'{qty}잔 / {option}')

order_coffee(3, 'iced')
order_coffee(3)

주의할 점은 기본값이 있는 파라미터는 기본값이 없는 파라미터의 뒤에 와야한다.

 

파라미터를 직접 가져와 입력하면 순서에 상관없이 입력할 수 있다.

def order_coffee(qty, option = 'hot'):
    print(f'{qty}잔 / {option}')

order_coffee(option ='iced', qty = 5)

 

return은 값을 반환시켜 다른 곳에 사용할 수 있도록 해준다.

def get_id(email):

    email_id = email.removesuffix('@test.com')
    print(email_id)

    return email_id

user_id = get_id('user@test.com')
print(user_id)

 

return이 없으면 user_id는 값이 없는 변수가 된다.

def get_id(email):

    email_id = email.removesuffix('@test.com')
    print(email_id)

    # return email_id

user_id = get_id('user@test.com')
print(user_id)

 

if 문을 활용한 함수

def get_id(email):

    if email.endswith('@test.com'):
        email_id = email.removesuffix('@test.com')
        print(email_id)
        return email_id
    else:
        print('처리할 수 없는 이메일 주소입니다.')

user_id = get_id('user@example.com')
print(user_id)

 

 

모듈

연관이 있는 함수들의 집합

모듈로 함수를 관리하게 되면 하나의 라이브러리처럼 만들어서 다양한 프로그램에 공통적으로 활용할 수 있다.

 

먼저 모듈로 사용할 파일을 만든다.

def get_id(email):

    if email.endswith('@test.com'):
        email_id = email.removesuffix('@test.com')
        print(email_id)
        return email_id
    else:
        print('처리할 수 없는 이메일 주소입니다.')

함수를 넣어준 뒤, 저장한다.

 

새로운 파일에서 모듈에 있는 함수를 불러와 활용할 수 있다.

from id_getter import get_id

user_id = get_id('user@test.com')
print(user_id)

from은 모듈의 파일명이고 import는 모듈에서 불러올 함수의 이름이다.

 

 

'Back-End > Python' 카테고리의 다른 글

객체지향  (0) 2023.08.09
회원가입 프로그램 실습 - 파이썬(Python) 편  (0) 2023.08.08
자료구조 - 리스트 / 튜플 / 딕셔너리  (0) 2023.07.27
조건문과 반복문  (0) 2023.07.20
변수와 자료형  (0) 2023.07.19

+ Recent posts