Python_TIL_06

Hanbin Lee·2021년 11월 19일
0

Python_TIL

목록 보기
6/10
post-thumbnail

파이썬의 함수에 대해 공부했던 내용을 정리하려 한다.

함수

함수는 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. print 함수에 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

REFERENCE

나도코딩 유튜브
Python - 공식문서
점프투파이썬 - WikiDocs

profile
안녕하세요 백엔드 개발자 이한빈 입니다 :)

1개의 댓글

comment-user-thumbnail
2025년 4월 8일

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

답글 달기