함수

- 호출 될 때만 실행되는 코드 블록

def my_function(): # 함수
  print("Hello from a function")

my_function() # 함수 호출

인수로 함수에 전달

함수 이름 뒤에 괄호 안에 지정

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

함수에 전달 될 인수의 수를 모르는 경우 *를 사용

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

key = value 구문을 사용하여 인수를 보낼 수도 있음

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

함수에 전달 될 키워드 인수의 수를 모르는 **사용

def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

인수없이 함수를 호출하면 기본값을 사용

def my_function(country = "Norway"): #기본값을 Norway로 사용
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

파이썬은 또한 함수 재귀를 받아들임

재귀함수는 함수가 자신을 호출 할 수 있음을 의미

def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1) #함수가 자신을 호출
    print(result)
  else:
    result = 0
  return result #return이 0 종료

print("\n\nRecursion Example Results")
tri_recursion(6)

 

출처

https://www.w3schools.com/python/python_functions.asp

'Python' 카테고리의 다른 글

반복문, 조건문  (0) 2021.06.17
Dictionary  (0) 2021.06.17
Set  (0) 2021.06.17
Tuple  (0) 2021.06.17
List  (0) 2021.06.17

+ Recent posts