본문 바로가기
add 깨알 공부

Python - 함수

by mihsyeh 2021. 7. 5.
나도코딩 강의를 듣고 복습의 의미로 작성하였습니다. 실제 강의 내용이나 예제와 다를 수 있습니다.

 

함수

 

1. 전달값과 반환값

- def 정의 만 가능, 호출 전까진 실행되지 않음

def open_account():
    print("새로운 계좌가 생성되었습니다.")
    
open_account()

 

def deposit(balance, money):
    print("입금이 완료되었습니다. 잔액은 {0} 원입니다." .format(balance + money))
    return balance + money
    
balance = 0
balance = deposit(balance, 1000)
print(balance)

 

def withdraw(balance, money):
    if balance >= money:
        print("출금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance - money))
        return balance - money
    else:
        print("출금이 완료되지 않았습니다. 잔액은 {0} 원입니다.".format(balance))
        return balance

balance = 0
balance = deposit(balance, 1000)
balance = withdraw(balance, 2000)
balance = withdraw(balance, 500)

print(balance)

withdraw 출금하려는 금액 2000은 1000보다 큰 값이므로 출력이 되지 않는다.

 

- 여러 개의 값 반환하기

def withdraw_night(balance, money):
    commisiion = 100
    return commisiion, balance - money - commisiion
    
balance = 0
balance = deposit(balance, 1000)

commission, balance = withdraw_night(balance, 500)
print("수수료 {0}원이며, 잔액은 {1}원입니다.".format(commission, balance))
print(balance)

 

2. 기본값

def profile(name, age, main_lang):
    print("이름 : {0}\t나이 : {1}\t특기 : {2}".format(name, age, specialty))
    
profile("카리나", 20, "dance")
profile("윈터", 19, "vocal")

 

- 함수에 기본값 설정하기

def profile(name, age=12, specialty="vocal"):
	print("이름 : {0}\t나이 : {1}\t특기 : {2}".format(name, age, specialty))

profile("카리나")
profile("윈터")

 

3. 키워드 값을 이용한 함수 호출

def profile(name, specialty, age):
    print(name, specialty, age)

profile(name="카리나", specialty="dance", age=20)
profile(age=19, name="윈터", specialty="vocal")

순서가 달라도 동일 출력가능

 

 

4. 가변함수

def profile(name, age, spec1, spec2, spec3, spec4, spec5):
    print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
    print(spec1, spec2, spec3, spec4, spec5)
    
profile("지젤", 20, "dance", "rap", "visual", "center", "actor")
profile("닝닝", 19, "vocal", "dance", "visual")

닝닝의 spec 값 개수가 부족하기 때문에 호출이 되지 않고 오류가 생긴다.

profile("지젤", 20, "dance", "rap", "visual", "center", "actor")
profile("닝닝", 19, "vocal", "dance", "visual", "", "")

맞게 출력하려면 빈칸을 만들어주거나 spec6, spec7 ... 등등 함수를 늘려야한다. 그럼 원하는 값대로 나오긴 나온다.

 

서로 다른 개수의 값을 넣어줄 때는 가변인자 즉 *로 시작되는 매개변수를 이용하면 된다.

def profile(name, age, *specialty):
    print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
    for spec in specialty:
        print(spec, end=" ")
    print()

profile("지젤", 20, "dance", "rap", "visual", "center", "actor")
profile("닝닝", 19, "vocal", "dance", "visual")

 

 

 

5. 지역변수, 전역변수

지역변수 : 함수 내에서만 사용할 수 있는 함수, 함수 호출될때 만들어졌다가 호출이 끝나면 사라지는것

전역변수 : 프로그램 내 어디서든 부를 수 있는 함수

 

gun = 10

def chekpoint(soldiers):
	gun = gun - soldiers
	print("[함수 내] 남은 총 : {0}".format(gun))

print("전체 총 : {0}".format(gun))
chekpoint(2)
print("남은 총 : {0}".format(gun))

 

chekpoint 함수 내에서 gun이 초기화가 되지 않았기 때문에 gun 함수가 할당되지 않아 출력이 되지 않는다.

 

gun = 10

def chekpoint(soldiers):
      gun = 20 # 지역변수
      global gun # 전역변수
    
      gun = gun - soldiers
      print("[함수 내] 남은 총 : {0}".format(gun))

print("전체 총 : {0}".format(gun))
chekpoint(2)
print("남은 총 : {0}".format(gun))

지역변수 gun = 20을 chekpoint 내에서 호출했을때 출력

전역변수 gun = 10을 넣어주기 위해 global gun을 호출했을때 출력

 

 

전역변수를 많이 쓰게되면 코드관리가 어려워 일반적으로 권장되지는 않는다. 가급적 함수의 전달값을 파라미터로 던져 계산 후 반환값을 받아 사용하는 방법을 쓴다.

def chekpoint_ret(gun, soldiers):
    gun = gun - soldiers
    print("[함수 내] 남은 총 : {0}".format(gun))
    return gun
    
print("전체 총 : {0}".format(gun))
gun = chekpoint_ret(gun, 2)
print("남은 총 : {0}".format(gun))

결과는 같다.

 

 

Quiz. 표준 체중을 구하는 프로그램을 작성하시오


<성별에 따른 공식>

여자 : 키(m) X 키(m) X 21
남자 : 키(m) X 키(m) X 22

<조건>

1. 표준 체중은 별도의 함수 내에서 계산
2. 표준 체중은 소수점 둘째자리까지 표시
<출력문 예>



더보기
def std_weght(height, gender)
	if gender == "여자":
		return height * height * 21
	else:
    	return height * height * 22

height = 173
gender = "남자"

weight = round(std_weight(height / 100, gender), 2)

print("키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, std_weght))

 

 

 

댓글