파이썬의 함수에 대해 공부했던 내용을 정리하려 한다.
함수는 def
를 사용하여 선언한다.
기본 형태
def 함수 이름(매개 변수): 함수 내용 함수 이름() # 실행
def open_account(): print("새로운 계좌가 생성되었습니다.") open_account() # "새로운 계좌가 생성되었습니다."
함수의 전달인자로 값을 전달하고,
return
을 사용하여 함수의 반환 값을 정할 수 있다.def deposit(balance, money): print("입금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance + money)) return balance + money def withdraw(balance, money): if balance >= money: print("출금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance - money)) return balance - money else: print("출금이 완료되지 않았습니다. 잔액은 {0} 원입니다.".format(balance)) return balance def withdraw_night(balance, money): commission = 100 return commission, balance - money - commission balance = 0 balance = deposit(balance, 2000) # return 2000 balance = withdraw(balance, 500) # return 1500 commission, balance = withdraw_night(balance, 500) # return [100, 900] print("수수료는 {0} 원이며, 잔액은 {1} 원입니다.".format(commission, balance))
함수의 매개변수에 기본 값을 할당하여 전달인자에 값이 전달되지 않더라도 원할하게 실행이 가능하다.
def profile(name, age=17, main_lang="파이썬"): print("이름 : {0}\t나이 : {1}\t주 사용 언어: {2}".format(name, age, main_lang)) profile("유재석") profile("김태호")
ps) 코드의 줄이 너무 길어질 때,
\
를 사용하여 코드의 줄을 바꿀 수 있다.def profile(name, age=17, main_lang="파이썬"): print("이름 : {0}\t나이 : {1}\t주 사용 언어: {2}"\ .format(name, age, main_lang))
함수의 매개변수를 안다면 키워드에 직접 지정하여 전달인자의 순서 상관없이 함수를 실행 할 수 있다.
def profile(name, age, main_lang): print(name, age, main_lang) profile(name="유재석", main_lang="파이썬", age=20) profile(main_lang="자바", age=25, name="김태호")
함수의 전달인자의 갯수가 특정되지 않을 때, 매개변수 앞에
*
를 사용하여 실행 할 수 있다.def profile(name, age, *language): print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ") for lang in language: print(lang, end=" ") print() profile("유재석", 20, "Python", "Java", "C", "C#") profile("김태호", 25, "Kotlin", "Swift")
ps.
end
키워드를 사용하면, 출력문 마지막를 핸들링 할 수 있다. 기본 값으론 줄 바꿈을 뜻하는\n
이다.
파이썬의 함수 내에서 외부에 있는 변수를 사용하기 위해서는
global
키워드를 사용하여 사용한다.gun = 10 def checkpoint(soldiers): global gun gun = gun - soldiers print("[함수 내] 남은 총 : {0}".format(gun)) def checkpoint_ret(gun, soldiers): gun = gun - soldiers print("[함수 내] 남은 총 : {0}".format(gun)) return gun print("전체 총 : {0}".format(gun)) # gun = 10 checkpoint(2) # gun = 8 gun = checkpoint_ret(gun, 2) # gun = 6 print("남은 총 : {0}".format(gun)) # gun = 6
When it comes to performance and minimal recoil, the glock 17 really stands out. I’m curious how it compares to other 9mm pistols in its class—would love to hear real user experiences. glock 17