[Python] 4.함수(Function)

img1.daumcdn.png

1.함수(Function)

함수는 특정 작업을 수행하는 코드 블록으로. `def` 키워드를 사용해 정의합니다.

def gray():
    print("gray")

gray() # gray

2. 매개변수와 인자

함수는 매개변수를 받아 특정 값을 기반으로 작업을 수행합니다.

  • 매개 변수 사용
def greek(name):
     print(f'Hello, {name}!')
greek('komma') # Hello, komma!
  • 여러 매개 변수
# parameter must
def add(a,b):
    return a + b

result = add(3,10)
print(result) # 3 + 10 = 13

3.기본 인자값

함수를 정의할 때 기본값 설정이 가능합니다.

def gray(name="gary"):
    print(f"Hello, {name}!");

gray();  # Hello gary!
gray("Afe") # Hello Afe!

4.반환 값

함수는 return 문을 사용해 값을 반환할 수 있습니다. 

def sqaure(x):
    return x * x;

result = sqaure(5)
print(result) # 25

5.가변 인자

함수에 가변 개수의 인자를 전달할 수 있습니다.

  • *args 사용
def add_multiple(*args):
    return sum(args)

result = add_multiple(1,2,3,4)
print(result) # 1 + 2 + 3 + 4
  • **kwargs 사용

키워드 인자를 가변적으로 전달할 수 있습니다.

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Komma", age=25);
# name: Komma
# age: 25

6.람다 함수

간단하게 함수를 한 줄로 정의할 수 있습니다.

square = lambda  x: x * x
print(square(10)) # 100

7. 함수의 고급 기능

  • 중첩 함수

함수 안에 다른 함수를 정의할 수 있습니다.

def other_function():
    def inner_function():
         return "inner_function"
    return inner_function()

print(other_function()) # inner_function
  • 클로저

내부 함수가 외부 함수의 변수를 기억하는 기능입니다.

def outer_function(x):
    def inner_function(y):
         return x * y
    return inner_function

add_25 = outer_function(25)
print(add_25(5)) # 125

 

GitHub - Koras02/python-blog

Contribute to Koras02/python-blog development by creating an account on GitHub.

github.com

 

LIST