1. 함수 정의
1def open_account():2print("새로운 계좌를 개설합니다.")345open_account() # 앞에 정의한 open_account() 함수 호출
2. 전달값과 반환값
2.1
1def open_account():2print("새로운 계좌를 개설합니다.")345open_account() # open_account() 함수 호출678def deposit(balance, money): # 입금 처리 함수9print("{0}원을 입금했습니다. 잔액은 {1}원입니다.".format(money, balance + money))10return balance + money # 입금 후 잔액 정보 반환111213balance = 0 # 초기 잔액, balance 변수에 초깃값으로 0 저장14balance = deposit(balance, 1000) # 1,000원 입금, balance 변수에 deposit() 함수의 반환값을 다시 저장15# deposit(balance, 1000)
2.2
1def open_account():2print("새로운 계좌를 개설합니다.")345open_account() # open_account() 함수 호출678def deposit(balance, money): # 입금 처리 함수9print("{0}원을 입금했습니다. 잔액은 {1}원입니다.".format(money, balance + money))10return balance + money # 입금 후 잔액 정보 반환111213def withdraw(balance, money): # 출금 처리 함수14if balance >= money: # 잔액이 출금액보다 많으면15print("{0}원을 출금했습니다. 잔액은 {1}원입니다.".format(money, balance - money))16return balance - money # 출금 후 잔액 반환17else:18print("잔액이 부족합니다. 잔액은 {0}원입니다.".format(balance))19return balance # 기존 잔액 반환202122balance = 0 # 초기 잔액23balance = deposit(balance, 1000) # 1,000원 입금2425# 출금26balance = withdraw(balance, 2000) # 2,000원 출금 시도27balance = withdraw(balance, 500) # 500원 출금 시도
2.3
1def open_account():2print("새로운 계좌를 개설합니다.")345open_account() # open_account() 함수 호출678def deposit(balance, money): # 입금 처리 함수9print("{0}원을 입금했습니다. 잔액은 {1}원입니다.".format(money, balance + money))10return balance + money # 입금 후 잔액 정보 반환111213def withdraw_night(balance, money): # 업무 시간 외 출금14commission = 100 # 출금 수수료 100원15print("업무 시간 외에 {}원을 출금했습니다.".format(money))16return commission, balance - money - commission171819balance = 0 # 초기 잔액20balance = deposit(balance, 1000) # 1,000원 입금2122# 업무 시간 외 출금 시도23commission, balance = withdraw_night(balance, 500)24print("수수료 {0}원이며, 잔액은 {1}원입니다.".format(commission, balance))252627(name, age, hobby) = ("피글렛", 20, "코딩") # 변수명에 소괄호가 없어도 실행결과는 동일28print(name, age, hobby)2930name, age, hobby = ("피글렛", 20, "코딩") # 변수명에 소괄호가 없어도 실행결과는 동일31print(name, age, hobby)3233name, age, hobby = "피글렛", 20, "코딩" # 값에 소괄호가 없어도 실행결과는 동일34print(name, age, hobby)
3. 함수 호출
3.1
1def profile(name, age, main_lang):2print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}".format(name, age, main_lang))345profile("찰리", 20, "파이썬")6profile("루시", 25, "자바")789def profile(name, age=20, main_lang="파이썬"):10print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}".format(name, age, main_lang))111213profile("찰리")14profile("루시")151617def profile(name, age=20, main_lang="파이썬"):18print("이름 : {0}\t나이 : {1}\t주 사용 언어 : {2}".format(name, age, main_lang))192021profile("찰리") # age, main_lang은 기본값 사용22profile("찰리", 22) # main_lang은 기본값 사용23profile("찰리", 24, "자바") # 기본값을 사용하지 않음242526# 마트에서 2가지 상품을 구매하는 경우27def buy(item1, item2="음료수"): # 올바른 함수 정의: 일반 전달값을 먼저 작성28print(item1, item2)293031buy("빵") # item1=빵, item2=음료수3233"""34# 마트에서 2가지 상품을 구매하는 경우35def buy(item1="음료수", item2): # 잘못된 함수 정의: 기본값을 가지는 전달값을 먼저 작성36print(item1, item2)3738buy("빵") # item1=빵? item2=빵?39"""
3.2 키워드 값
1def profile(name, age, main_lang): # 키워드 인자 : name, age, main_lang2print(name, age, main_lang)345profile(name="찰리", main_lang="파이썬", age=20)6profile(main_lang="자바", age=25, name="루시")789def profile(name, age, main_lang): # 키워드 인자 : name, age, main_lang10print(name, age, main_lang)111213profile("찰리", age=20, main_lang="파이썬") # 올바른 함수 호출: 일반 전달값을 먼저 작성14# profile(name="루시", 25, "파이썬") # 잘못된 함수 호출: 키워드 인자를 먼저 작성151617def profile(name, age, main_lang):18print(name, age, main_lang)1920profile("찰리", 20, "파이썬") # 위치 인자: "찰리", 20, "파이썬"
3.3 가변인자
1# 7.3.32def profile(name, age, lang1, lang2, lang3, lang4, lang5):3print("이름 : {0}\t나이 : {1}\t".format(name, age))4print(lang1, lang2, lang3, lang4, lang5)567profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#")8profile("루시", 25, "코틀린", "스위프트", "", "", "")91011def profile(name, age, lang1, lang2, lang3, lang4, lang5):12print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ") # 줄 바꿈 대신 띄어쓰기13print(lang1, lang2, lang3, lang4, lang5)141516profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#")17profile("루시", 25, "코틀린", "스위프트", "", "", "")181920def profile(name, age, *language):21print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")22print(language, type(language))232425profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#", "자바스크립트") # 자바스크립트 추가26profile("루시", 25, "코틀린", "스위프트")272829def profile(name, age, *language):30print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")31# print(language, type(language))32for lang in language:33print(lang, end=" ") # 언어를 모두 한 줄에 표시34print() # 줄 바꿈 목적353637profile("찰리", 20, "파이썬", "자바", "C", "C++", "C#", "자바스크립트")38profile("루시", 25, "코틀린", "스위프트")394041def add(item):42print(item, "붓기")434445def americano():46add("뜨거운 물")47add("에스프레소")484950print("아메리카노 만드는 법")51americano()
4. 변수의 범위, 지역변수, 전역변수
1glasses = 10 # 전체 3D 안경 개수: 10개234def rent(people): # 3D 안경을 대여한 관객 수5# glasses = 20 # 변수 정의 추가6# global glasses # 전역 공간에 있는 glasses 변수를 함수 안에서 사용하겠다는 표시7glasses = glasses - people # 잔여 3D 안경 개수 = 전체 개수 - 대여한 개수8print("[함수 내부] 남은 3D 안경 개수: {0}".format(glasses))91011print("전체 3D 안경 개수: {0}".format(glasses))12rent(2) # 3D 안경을 대여한 관객이 2명일 때13print("남은 3D 안경 개수: {0}".format(glasses))1415glasses = 10161718def rent_return(glasses, people): # 전체 3D 안경 수와 대여 관객 수를 전달받음19glasses = glasses - people # 전달값을 담은 glasses 사용20print("[함수 내부] 남은 3D 안경 개수: {0}".format(glasses))21return glasses222324print("전체 3D 안경 개수: {0}".format(glasses))25glasses = rent_return(glasses, 2) # 함수 안에서 수정된 glasses 값을 반환받음26print("남은 3D 안경 개수: {0}".format(glasses))
5. 퀴즈. 표준체중구하기
1"""2Quiz) 표준 체중을 구하는 프로그램을 작성하시오3* 표준 체중 : 각 개인의 키에 적당한 체중45(성별에 따른 공식)6남자 : 키(m) x 키(m) x 227여자 : 키(m) x 키(m) x 2189조건1 : 표준 체중은 별도의 함수 내에서 계산10* 함수명 : std_weight11* 전달값 : 키(height), 성별(gender)12조건2 : 표준 체중은 소수점 둘째자리까지 표시1314(출력 예제)15키 175cm 남자의 표준 체중은 67.38kg 입니다.16"""171819def std_weight(height, gender): # 표준 체중 계산 함수 정의20if gender == "남자":21return height * height * 2222else:23return height * height * 21242526height = 175 # 전달값(키, cm 단위)을 저장한 변수 정의27gender = "남자" # 전달값(성별)을 저장한 변수 정의28# weight = std_weight(height / 100, gender) # 함수 호출(키는 cm 단위에서 m 단위로 변환)29weight = round(std_weight(height / 100, gender), 2) # 반올림해서 소수점 둘째 자리까지 표시30print("키 {0}cm {1}의 표준 체중은 {2}kg입니다.".format(height, gender, weight))