Defining Functions
Functions in Python are blocks of reusable code that perform specific tasks. They help organize and structure your code, make it more modular, and reduce redundancy. You can define your own functions to encapsulate functionality and reuse it whenever needed.
1. Function Definition
To define a function in Python, you use the def
keyword followed by the function name and a pair of parentheses. Inside the parentheses, you can specify parameters (inputs) that the function accepts. The function body, indented below the def
statement, contains the code to be executed when the function is called.
Here's the basic structure of a function:
def function_name(parameter1, parameter2, ...):
# Function code here
For example, a simple function that adds two numbers:
def add_numbers(x, y):
result = x + y
return result
In this example, add_numbers
is the function name, and it accepts two parameters, x
and y
. The function calculates the sum and returns it using the return
statement.
2. Calling Functions
Once a function is defined, you can call it by using its name followed by parentheses. If the function has parameters, you provide values for those parameters in the parentheses.
result = add_numbers(5, 7)
In this case, the add_numbers
function is called with arguments 5
and 7
. The result of the function is stored in the result
variable.
3. Return Statements
Functions can return values using the return
statement. The value returned by the function can be used in expressions, assignments, or other operations.
For example, the add_numbers
function returns the result of adding two numbers:
def add_numbers(x, y):
result = x + y
return result
You can capture the result of the function call in a variable:
total = add_numbers(3, 4)
The total
variable will hold the value 7
.
4. Default Parameters
You can assign default values to function parameters. These defaults are used if no value is provided for the corresponding parameter when calling the function. For example:
def greet(name="Guest"):
return f"Hello, {name}!"
message = greet()
If you call greet()
without providing a name, it defaults to "Guest," and message
will contain "Hello, Guest!".
5. Docstrings
It's a good practice to include a docstring (a multi-line string within the function) to describe the purpose of the function and its parameters. This documentation is accessible using the help()
function.
def add_numbers(x, y):
"""
Add two numbers and return the result.
Parameters:
x (int): The first number to add.
y (int): The second number to add.
Returns:
int: The sum of x and y.
"""
result = x + y
return result
Use help(function_name)
or function_name.__doc__
to access the docstring for the function.
Functions in Python help improve code readability, reusability, and maintainability. They allow you to encapsulate logic, making your programs more modular and easier to understand.