In Python, a function is a block of code that performs a specific task. It allows you to modularize your code by breaking it into smaller, reusable pieces. Functions help improve code readability, reusability, and maintainability. Here's an introduction to functions in Python:
1. Defining Functions:
You can define a function using the def keyword followed by the function name, parameters in parentheses, a colon, and the function body indented underneath.
def greet(name): print(f"Hello, {name}!")
# Calling the function greet("Alice")
2. Function Parameters:
Parameters are values that a function expects to receive when it's called.
You can define multiple parameters separated by commas.
Parameters can have default values, making them optional when calling the function.
def add(a, b=0): return a + b
result = add(5, 3) # result is 8 result = add(5) # result is 5 (b uses default value)
3. Return Values:
Functions can return values using the return statement.
You can return any data type, including tuples, lists, or even other functions.
def square(x): return x * x
squared_value = square(4) # squared_value is 16
4. Scope:
Variables defined inside a function are local to that function's scope and are not accessible outside it.
Variables defined outside a function are global and can be accessed inside the function.
Docstrings:
You can add docstrings (documentation strings) to describe what a function does.
Docstrings are enclosed in triple quotes and are used for documentation purposes.
def divide(a, b): """ Divide two numbers.
Args: a (float): The numerator. b (float): The denominator.
Returns: float: The result of the division. """ return a / b
5. Lambda Functions:
Lambda functions (also known as anonymous functions) are small, inline functions defined using the lambda keyword.
They are often used for simple operations.
double = lambda x: x * 2 result = double(5) # result is 10
6. Function as an Argument:
Functions can be passed as arguments to other functions.