🎉 berenickt 블로그에 온 걸 환영합니다. 🎉
Lang
python
06-함수

1. 함수 정의

1
def open_account():
2
print("새로운 계좌를 개설합니다.")
3
4
5
open_account() # 앞에 정의한 open_account() 함수 호출

2. 전달값과 반환값

2.1

1
def open_account():
2
print("새로운 계좌를 개설합니다.")
3
4
5
open_account() # open_account() 함수 호출
6
7
8
def deposit(balance, money): # 입금 처리 함수
9
print("{0}원을 입금했습니다. 잔액은 {1}원입니다.".format(money, balance + money))
10
return balance + money # 입금 후 잔액 정보 반환
11
12
13
balance = 0 # 초기 잔액, balance 변수에 초깃값으로 0 저장
14
balance = deposit(balance, 1000) # 1,000원 입금, balance 변수에 deposit() 함수의 반환값을 다시 저장
15
# deposit(balance, 1000)

2.2

1
def open_account():
2
print("새로운 계좌를 개설합니다.")
3
4
5
open_account() # open_account() 함수 호출
6
7
8
def deposit(balance, money): # 입금 처리 함수
9
print("{0}원을 입금했습니다. 잔액은 {1}원입니다.".format(money, balance + money))
10
return balance + money # 입금 후 잔액 정보 반환
11
12
13
def withdraw(balance, money): # 출금 처리 함수
14
if balance >= money: # 잔액이 출금액보다 많으면
15
print("{0}원을 출금했습니다. 잔액은 {1}원입니다.".format(money, balance - money))
16
return balance - money # 출금 후 잔액 반환
17
else:
18
print("잔액이 부족합니다. 잔액은 {0}원입니다.".format(balance))
19
return balance # 기존 잔액 반환
20
21
22
balance = 0 # 초기 잔액
23
balance = deposit(balance, 1000) # 1,000원 입금
24
25
# 출금
26
balance = withdraw(balance, 2000) # 2,000원 출금 시도
27
balance = withdraw(balance, 500) # 500원 출금 시도

2.3

1
def open_account():
2
print("새로운 계좌를 개설합니다.")
3
4
5
open_account() # open_account() 함수 호출
6
7
8
def deposit(balance, money): # 입금 처리 함수
9
print("{0}원을 입금했습니다. 잔액은 {1}원입니다.".format(money, balance + money))
10
return balance + money # 입금 후 잔액 정보 반환
11
12
13
def withdraw_night(balance, money): # 업무 시간 외 출금
14
commission = 100 # 출금 수수료 100원
15
print("업무 시간 외에 {}원을 출금했습니다.".format(money))
16
return commission, balance - money - commission
17
18
19
balance = 0 # 초기 잔액
20
balance = deposit(balance, 1000) # 1,000원 입금
21
22
# 업무 시간 외 출금 시도
23
commission, balance = withdraw_night(balance, 500)
24
print("수수료 {0}원이며, 잔액은 {1}원입니다.".format(commission, balance))
25
26
27
(name, age, hobby) = ("피글렛", 20, "코딩") # 변수명에 소괄호가 없어도 실행결과는 동일
28
print(name, age, hobby)
29
30
name, age, hobby = ("피글렛", 20, "코딩") # 변수명에 소괄호가 없어도 실행결과는 동일
31
print(name, age, hobby)
32
33
name, age, hobby = "피글렛", 20, "코딩" # 값에 소괄호가 없어도 실행결과는 동일
34
print(name, age, hobby)

3. 함수 호출

3.1

1
def profile(name, age, main_lang):
2
print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}".format(name, age, main_lang))
3
4
5
profile("찰리", 20, "파이썬")
6
profile("루시", 25, "자바")
7
8
9
def profile(name, age=20, main_lang="파이썬"):
10
print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}".format(name, age, main_lang))
11
12
13
profile("찰리")
14
profile("루시")
15
16
17
def profile(name, age=20, main_lang="파이썬"):
18
print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}".format(name, age, main_lang))
19
20
21
profile("찰리") # age, main_lang은 기본값 사용
22
profile("찰리", 22) # main_lang은 기본값 사용
23
profile("찰리", 24, "자바") # 기본값을 사용하지 않음
24
25
26
# 마트에서 2가지 상품을 구매하는 경우
27
def buy(item1, item2="음료수"): # 올바른 함수 정의: 일반 전달값을 먼저 작성
28
print(item1, item2)
29
30
31
buy("빵") # item1=빵, item2=음료수
32
33
"""
34
# 마트에서 2가지 상품을 구매하는 경우
35
def buy(item1="음료수", item2): # 잘못된 함수 정의: 기본값을 가지는 전달값을 먼저 작성
36
print(item1, item2)
37
38
buy("빵") # item1=빵? item2=빵?
39
"""

3.2 키워드 값

1
def profile(name, age, main_lang): # 키워드 인자 : name, age, main_lang
2
print(name, age, main_lang)
3
4
5
profile(name="찰리", main_lang="파이썬", age=20)
6
profile(main_lang="자바", age=25, name="루시")
7
8
9
def profile(name, age, main_lang): # 키워드 인자 : name, age, main_lang
10
print(name, age, main_lang)
11
12
13
profile("찰리", age=20, main_lang="파이썬") # 올바른 함수 호출: 일반 전달값을 먼저 작성
14
# profile(name="루시", 25, "파이썬") # 잘못된 함수 호출: 키워드 인자를 먼저 작성
15
16
17
def profile(name, age, main_lang):
18
print(name, age, main_lang)
19
20
profile("찰리", 20, "파이썬") # 위치 인자: "찰리", 20, "파이썬"

3.3 가변인자

1
# 7.3.3
2
def profile(name, age, lang1, lang2, lang3, lang4, lang5):
3
print("이름 : {0}\t나이 : {1}\t".format(name, age))
4
print(lang1, lang2, lang3, lang4, lang5)
5
6
7
profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#")
8
profile("루시", 25, "코틀린", "스위프트", "", "", "")
9
10
11
def profile(name, age, lang1, lang2, lang3, lang4, lang5):
12
print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ") # 줄 바꿈 대신 띄어쓰기
13
print(lang1, lang2, lang3, lang4, lang5)
14
15
16
profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#")
17
profile("루시", 25, "코틀린", "스위프트", "", "", "")
18
19
20
def profile(name, age, *language):
21
print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
22
print(language, type(language))
23
24
25
profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#", "자바스크립트") # 자바스크립트 추가
26
profile("루시", 25, "코틀린", "스위프트")
27
28
29
def profile(name, age, *language):
30
print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
31
# print(language, type(language))
32
for lang in language:
33
print(lang, end=" ") # 언어를 모두 한 줄에 표시
34
print() # 줄 바꿈 목적
35
36
37
profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#", "자바스크립트")
38
profile("루시", 25, "코틀린", "스위프트")
39
40
41
def add(item):
42
print(item, "붓기")
43
44
45
def americano():
46
add("뜨거운 물")
47
add("에스프레소")
48
49
50
print("아메리카노 만드는 법")
51
americano()

4. 변수의 범위, 지역변수, 전역변수

1
glasses = 10 # 전체 3D 안경 개수: 10개
2
3
4
def rent(people): # 3D 안경을 대여한 관객 수
5
# glasses = 20 # 변수 정의 추가
6
# global glasses # 전역 공간에 있는 glasses 변수를 함수 안에서 사용하겠다는 표시
7
glasses = glasses - people # 잔여 3D 안경 개수 = 전체 개수 - 대여한 개수
8
print("[함수 내부] 남은 3D 안경 개수: {0}".format(glasses))
9
10
11
print("전체 3D 안경 개수: {0}".format(glasses))
12
rent(2) # 3D 안경을 대여한 관객이 2명일 때
13
print("남은 3D 안경 개수: {0}".format(glasses))
14
15
glasses = 10
16
17
18
def rent_return(glasses, people): # 전체 3D 안경 수와 대여 관객 수를 전달받음
19
glasses = glasses - people # 전달값을 담은 glasses 사용
20
print("[함수 내부] 남은 3D 안경 개수: {0}".format(glasses))
21
return glasses
22
23
24
print("전체 3D 안경 개수: {0}".format(glasses))
25
glasses = rent_return(glasses, 2) # 함수 안에서 수정된 glasses 값을 반환받음
26
print("남은 3D 안경 개수: {0}".format(glasses))

5. 퀴즈. 표준체중구하기

1
"""
2
Quiz) 표준 체중을 구하는 프로그램을 작성하시오
3
* 표준 체중 : 각 개인의 키에 적당한 체중
4
5
(성별에 따른 공식)
6
남자 : 키(m) x 키(m) x 22
7
여자 : 키(m) x 키(m) x 21
8
9
조건1 : 표준 체중은 별도의 함수 내에서 계산
10
* 함수명 : std_weight
11
* 전달값 : 키(height), 성별(gender)
12
조건2 : 표준 체중은 소수점 둘째자리까지 표시
13
14
(출력 예제)
15
키 175cm 남자의 표준 체중은 67.38kg 입니다.
16
"""
17
18
19
def std_weight(height, gender): # 표준 체중 계산 함수 정의
20
if gender == "남자":
21
return height * height * 22
22
else:
23
return height * height * 21
24
25
26
height = 175 # 전달값(키, cm 단위)을 저장한 변수 정의
27
gender = "남자" # 전달값(성별)을 저장한 변수 정의
28
# weight = std_weight(height / 100, gender) # 함수 호출(키는 cm 단위에서 m 단위로 변환)
29
weight = round(std_weight(height / 100, gender), 2) # 반올림해서 소수점 둘째 자리까지 표시
30
print("키 {0}cm {1}의 표준 체중은 {2}kg입니다.".format(height, gender, weight))