Python 시작하기 (10부): 함수 사용
Source: Dev.to
함수 사용하기
이 글에서는 함수에 대해 배웁니다. 함수를 사용하면 특정 작업을 재사용할 수 있고, 더 깔끔하고 유지보수가 쉬운 코드를 작성할 수 있습니다.
함수는 def 문을 사용해 정의합니다. 함수를 정의한 뒤에는 호출(실행) 해야 내부 코드를 실행할 수 있습니다.
def function_name():
"""Function description"""
process
# Call the function
function_name()
예시
# Define a function
def say_hello():
"""A function that prints a greeting"""
print("Hello, Python!!")
# Call the function
say_hello() # Hello, Python!!
# 정의된 함수는 원하는 만큼 호출할 수 있습니다
say_hello() # Hello, Python!!
say_hello() # Hello, Python!!
say_hello() # Hello, Python!!
인자 사용하기
인자를 사용하면 더 유연한 함수를 만들 수 있습니다.
def function_name(argument):
"""Function description"""
process
예시
# Define a function with one argument
def say_hello(lang):
"""A function that greets in a chosen language"""
print("Hello, " + lang + "!!")
# Call the function
say_hello("Python") # Hello, Python!!
say_hello("Rust") # Hello, Rust!!
say_hello("Kotlin") # Hello, Kotlin!!
say_hello("Swift") # Hello, Swift!!
여러 인자 사용하기
필요한 만큼 인자를 정의할 수 있습니다.
def function_name(arg1, arg2, arg3, ...):
"""Function description"""
process
예시
# Define a function with two arguments
def say_hello(greet, lang):
"""A function that combines a greeting with a language"""
print(greet + ", " + lang + "!!")
# Call the function
say_hello("Hello", "Python") # Hello, Python!!
say_hello("Ciao", "C/C++") # Ciao, C/C++!!
say_hello("Bonjour", "Java") # Bonjour, Java!!
say_hello("Namaste", "JavaScript") # Namaste, JavaScript!!
반환값 사용하기
return을 사용하면 함수가 일부 처리를 수행한 뒤 결과를 호출자에게 반환할 수 있습니다. 함수가 return을 사용하지 않으면 None을 반환하는 것으로 간주됩니다.
def function_name(arg1, arg2, arg3, ...):
"""Function description"""
process
return result
예시 – 숫자 두 배 만들기
def calc_double(num):
"""A function that returns double the value"""
return num * 2
print(calc_double(10)) # 20
print(calc_double(20)) # 40
print(calc_double(30)) # 60
예시 – 두 숫자 더하기
def calc_total(num1, num2):
"""A function that returns the sum of two numbers"""
return num1 + num2
print(calc_total(10, 20)) # 30
print(calc_total(30, 40)) # 70
print(calc_total(50, 60)) # 110
인자와 반환값은 함께 사용되는 경우가 많으니 두 개념을 모두 잘 이해해 두세요.
다음 내용은?
읽어 주셔서 감사합니다! 다음 글에서는 모듈에 대해 배울 예정입니다.
“Getting Started with Python (Part 8): Using Modules”
계속 기대해 주세요! 🚀