Python
Python_G-008. Function
X25WLK
2025. 1. 16. 11:56
Definition | A block of reusable code that performs a specific task. | def function_name(parameters): |
Syntax | def function_name(): | def greet(name): |
Calling a Function | Executing a function by using its name followed (by parentheses and arguments if needed) |
greet("Alice") |
Parameters | Variables listed inside the parentheses in the function definition. |
def add(a, b): |
Arguments | Values passed to the function when calling it. | add(3, 5) |
Return Statement | Used to return a value from a function. | return a + b |
Default Parameters | Parameters with default values that are used if no argument is provided. |
def greet(name="Guest"): |
Keyword Arguments | Arguments passed by specifying the parameter name. | describe_pet(pet_name="Whiskers", animal_type="cat") |
Lambda Functions | Small anonymous functions defined using the lambda keyword. |
square = lambda x: x * x |
Docstrings | A special string that describes the function's purpose and behavior, placed at the beginning of the function body. | """This function greets the person with the given name.""" |
Example Code:
# Defining a function
def greet(name="Guest"):
"""This function greets the person with the given name."""
print(f"Hello, {name}!")
# Calling the function
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
# Function with parameters and return value
def add(a, b):
"""This function returns the sum of two numbers."""
return a + b
# Calling the function
result = add(3, 5) # Output: 8
print(result)
# Lambda function
square = lambda x: x * x
print(square(5)) # Output: 25
반응형