함수#
소개#
함수는 파이썬 프로그래밍의 핵심 요소로, 특정 작업을 수행하도록 설계된 재사용 가능하고 효율적인 코드 조각들을 묶어줍니다. 함수는 프로그램 내에서 여러 번 호출될 수 있으므로 코드 구성이 용이하고 코드 중복을 방지하는 데 도움이 됩니다. 또한 함수를 사용하면 디버깅이 훨씬 쉬워집니다.
def함수를 정의합니다.return반환하면 함수의 출력값이 메인 프로그램으로 다시 전송됩니다.
용법:
def function_name(parameters):
# Code to execute when the function is called.
return result # Optional, used to return a value.
매개변수 |
설명 |
|---|---|
|
함수에 붙이는 이름입니다. |
|
선택 사항입니다. 함수 호출 시 입력값을 받는 변수로, 함수에 데이터를 전달할 수 있습니다. |
|
선택 사항입니다. 함수가 호출자에게 결과를 반환할 수 있도록 합니다. 함수에 return 문이 포함되지 않으면 기본적으로 |
참고: 함수는 호출되기 전에 반드시 정의되어 있어야 합니다.
함수 정의 및 호출#
Functions with No Parameters#
함수에 입력이 필요하지 않은 경우 매개변수 없이 정의할 수 있습니다.
# Define a function to display a message.
def greeting():
controller.screen.print("Hello!")
# Call the function to display the message.
greeting()
Functions with Parameters#
함수에 매개변수를 추가하여 함수 작동에 필요한 정보를 전달할 수도 있습니다.
# Define a function with a parameter.
def named_greeting(name):
controller.screen.print("Hello, " + name + "!")
named_greeting("Stranger")
Functions with Default Arguments#
기본 인수란 함수 호출 시 해당 인수에 대한 값이 제공되지 않으면 기본값을 사용하는 매개변수입니다.
# Define a function with a parameter and a default argument.
def named_greeting(name = "Stranger"):
controller.screen.print("Hello, " + name + "!")
# Use the default argument.
named_greeting()
controller.screen.next_row()
# Change the parameter to a different name.
named_greeting("AIR")
Return Values from Functions#
함수는 return 키워드를 사용하여 호출자에게 데이터를 반환할 수 있습니다. 이를 통해 프로그램에서 출력을 캡처하고 사용할 수 있습니다.
# Define a function that multiplies numbers by 2.
def times_two(number):
return number * 2
# Display the return value.
controller.screen.print(times_two(2))