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
'Python' 카테고리의 다른 글
Python_G-010. class vs instance (0) | 2025.01.17 |
---|---|
Python_G-009. import vs from ... import vs from... import * (0) | 2025.01.17 |
Python_G-007. List vs Tuple vs set vs dictionary (0) | 2025.01.16 |
Python_G-006. 10 Basic Plot (with Matplotlib) (0) | 2025.01.12 |
Python_G-005. Loop Type (0) | 2025.01.12 |