Functions in Python
Functions are reusable blocks of code that perform specific tasks. They help organize your code, improve readability, and promote modularity.
Defining Functions
Python
def function_name(parameters): """Function documentation""" # Function body return valuefunction_name: The name of the function.parameters: Optional parameters that the function can accept.return value: Optional return value of the function.
Calling Functions
Python
result = function_name(arguments)Example:
Python
def greet(name): """Greets the user with a personalized message.""" print(f"Hello, {name}!") greet("Alice") # Output: Hello, Alice!Parameters and Arguments
- Parameters: Variables defined within the function's parentheses.
- Arguments: Values passed to the function when it's called.
Return Values
- Functions can
optionally return a value using the
returnstatement. - If a function doesn't
have a
returnstatement, it implicitly returnsNone.
Default Parameters
Python
def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") greet("Alice") # Output: Hello, Alice!greet("Bob", "Hi") # Output: Hi, Bob!Keyword Arguments
Python
def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") greet(name="Alice", greeting="Hi")Variable-Length Arguments
- Arbitrary number of positional arguments:
Python
def greet(*names): for name in names: print(f"Hello, {name}!")- Arbitrary number of keyword arguments:
Python
def greet(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")Docstrings
- Use docstrings (triple-quoted strings) to document functions.
- They provide information about the function's purpose, parameters, and return value.
Best Practices:
- Use descriptive function names.
- Keep functions small and focused.
- Avoid excessive nesting.
- Write clear and concise docstrings.
By following these guidelines, you can write well-structured and maintainable functions in Python.