7. 함수 및 모듈

🌈 devleeky16498·2022년 6월 4일
0
### 함수 개념 정리 ###

def open_account(): #함수 정의는 def라는 키워드와 ()클로저로 정의해준다.
    print("새로운 계좌가 생성되었습니다.")

#()안은 파라미터이며, 인스턴스 파라미터를 사용해도 self라는 파라미터를 넣어주어야 한다.
#아무것도 명시하지 않는 경우는  Void리턴으로 간주된다.
open_account()

#파라미터를 어떻게 대입하는지 알아봅세다.

def deposit(balance, money):
    print("입금이 완료되었습니다. 잔액은 {0}입니다.".format(balance + money))
    return balance + money
# return 키워드를 입력하면 다음과 같이 반환값을 받아서 사용할 수 있다.

balance = 0
balance = deposit(100, 10)
print(balance)
# deposit메서드의 반환값을 변수에 넣어주는 모습이다.

def withdraw(balance, money):
    if balance < money:
        print("돈이 부족합니다.")
        return balance
    else:
        print("출금이 완료되었습니다. 잔액은 {0}입니다.".format(balance - money))
        return balance - money

balance = 100
balance = withdraw(balance, 20)
print(balance)

def withdraw_night(balance, money):
    commission = 10 # 수수료 10원
    return commission, balance - money - commission


balance = withdraw_night(balance, 10)
print(balance)
#무섭다...그냥 자유롭게 되게 자유롭게 자료형 통제가 가능하다...이 언어 미쳤네 ㅋㅋㅋㅋㅋ

def profile(name, age, main_lang):
    print("이름 : {0}, 나이 : {1}, 주사용 언어 : {2}"\
        .format(name, age, main_lang))
        #역 슬래시 하고 저렇게 명시를 해주게 되면 그냥 같은 한줄의 코드이다.

profile("유재석", 20, "파이선")
profile("김태호", 25, "자바")

#만약 파라미터에 기본값을 설정하고 싶다면?

def profile1(name, age = 20, main_lang = "Python"):
    print("이름 : {0}, 나이 : {1}, 주사용 언어 : {2}"\
        .format(name, age, main_lang))
        #역 슬래시 하고 저렇게 명시를 해주게 되면 그냥 같은 한줄의 코드이다.

profile1("유재석")
profile1("김태호")

# 키워드 값을 활용한 함수

def profile2(name, age, main_lang):
    print(name, age, main_lang)

profile2(name = "유재석", main_lang="파이선", age = 25)
#단순하게 키워드에 해당하는 값이 순서가 섞여도 자연스럽게 잘 들어가게 된다.


# 가변인자 함수 호출
# def profile4(name, age, lang1, lang2, lang3, lang4, lang5):
#     print("이름 : {0}\t나이 : {1}\t".format(name, age), end = " ")
#     print(lang1, lang2, lang3, lang4, lang5)

def profile4(name, age, *language):
    print("이름 : {0}\t나이 : {1}\t".format(name, age), end = " ")
    for lang in language:
        print(lang, end = " ")
    print()
    #다음과 같이 *표를 해주게 되면 가변 인자로 무엇이든 원하는 만큼 대입을 해주는 것이 가능하다.

profile4("유재석", 20, "자바", "자바", "자바", "자바", "자바")
profile4("김태호", 23, "자바", "자바")

### 모듈 개념 ###

## 모듈이라 함은 일반적으로 사용 목적을 지닌 코드들의 묶음이라고 생각하면 된다.
## 다음처럼 모듈 안에는 다양한 함수가 구현되어 있다.

#일반 가격

def price(people):
    print("{0} 명 가격은 {1} 입니다.".format(people, people*10000))

#조조할인

def price_morning(people):
    print("{0} 명 가격은 {1} 입니다.".format(people, people*6000))

#군인할인

def price_soldier(soldiers):
    print("{0} 명 가격은 {1} 입니다.".format(soldiers, soldiers*4000))

# 모듈은 같은 파일 경로내에서만 소통이 가능하다.

### 모듈 사용의 예시이다.

# import theater_module

# theater_module.price(3) # 3명이서 영화보러 가면?
# theater_module.price_morning(3)# 3명 조조할인 가격?

# 다음처럼 import를 통해서 모듈간의 소통이 가능하다.

# import theater_module as mv # as뒤에 붙여주면 별명을 지어줄 수 있다.

# mv.price(3)
# mv.price_morning(3)
# mv.price_soldier(3)

# 모듈명을 다음처럼 축약가능하다.

# from theater_module import *
# price(3)
# price_morning(3)
# price_soldier(3)

# from을 써주게 되면 바로바로 그냥 . 없이 바로 사용 가능하다.

# from theater_module import price, price_morning
# price(5)
# price_morning(5)
# price_soldier(7)
# 우측에 쓰기로 한 함수로 정의하지 않았으므로 인식을 못한다.

# 쓸 함수 자체에 대해서도 별명을 지어서 편하게 쓸 수 있다.
from theater_module import price_soldier as ps
ps(3)
profile
Welcome to Growing iOS developer's Blog! Enjoy!🔥

0개의 댓글