Python Functions
In Python, a function is a block of reusable code that performs a specific task. Functions help organize code into smaller, modular chunks, making it more readable and maintainable. You can define a function once and call it multiple times throughout your program.
1. Defining a Function
You can define a function using the def keyword, followed by the function name and parentheses (). Any parameters the function accepts go inside the parentheses.
Basic Syntax:
def function_name(parameters):
# Code block
# Optional: return value
2. Example of a Simple Function
Here’s a simple example of defining and calling a function that prints a greeting:
def greet():
print("Hello, welcome to Python!")
# Calling the function
greet()
Output:
Hello, welcome to Python!
In this example, the function greet() is defined with no parameters, and when called, it prints a greeting message.
3. Functions with Parameters
Functions can accept parameters (also called arguments) that allow you to pass values into the function when calling it.
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!
In this example, the function greet takes one parameter name and prints a personalized greeting based on the argument passed to it when calling the function.
4. Returning Values from Functions
Functions can return values using the return statement. This allows you to pass a result back to the caller for further use.
Example:
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8
In this example, the add function takes two parameters a and b, adds them together, and returns the result.
5. Default Parameters
You can specify default values for parameters in the function definition. If no argument is passed for that parameter when calling the function, the default value is used.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet("Alice")
greet()
Output:
Hello, Alice!
Hello, Guest!
Here, the greet function has a default parameter name="Guest", which is used when no argument is passed.
6. Keyword Arguments
In Python, you can pass arguments to a function by specifying the parameter names. These are known as keyword arguments.
Example:
def introduce(name, age):
print(f"Name: {name}, Age: {age}")
introduce(age=25, name="Alice")
Output:
Name: Alice, Age: 25
In this example, we pass the arguments by name, and Python assigns them to the corresponding parameters in the function.
7. Variable Number of Arguments (Arbitrary Arguments)
If you don’t know how many arguments will be passed to a function, you can use *args (for non-keyword arguments) and **kwargs (for keyword arguments) to allow a variable number of arguments.
Example with *args:
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
print(add_numbers(1, 2, 3))
print(add_numbers(5, 10, 15, 20))
Output:
6
50
In this example, *args allows the function add_numbers to accept any number of positional arguments. It adds all the arguments together and returns the total.
Example with **kwargs:
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="New York")
Output:
name: Alice
age: 25
city: New York
Here, **kwargs allows the function to accept an arbitrary number of keyword arguments, which are passed as a dictionary.
8. Lambda Functions (Anonymous Functions)
A lambda function is a small anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression. Lambda functions are often used for short, simple operations.
Example:
add = lambda x, y: x + y
print(add(5, 3))
Output:
8
In this example, the lambda function takes two arguments x and y, and returns their sum.
9. Function Scope (Local and Global Variables)
In Python, variables defined inside a function are local variables and can only be accessed within that function. Variables defined outside the function are global variables and can be accessed anywhere in the code.
Example:
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print("Inside function:", x)
my_function()
print("Outside function:", x)
Output:
Inside function: 5
Outside function: 10
In this example, the local variable x inside my_function does not affect the global variable x, because they exist in different scopes.
10. Docstrings (Function Documentation)
You can add a docstring to your function, which is a string that describes what the function does. The docstring should be placed immediately after the def line.
Example:
def greet(name):
"""
This function prints a greeting message to the user.
Parameters:
name (str): The name of the user.
"""
print(f"Hello, {name}!")
greet("Alice")
Docstrings are useful for documenting the function’s purpose, parameters, and return values, making your code easier to understand for others (or for yourself in the future).
Summary of Functions in Python:
- Defining a function: Use the
defkeyword. - Parameters: Functions can accept parameters for more flexible code.
- Returning values: Use
returnto pass results back to the caller. - Default parameters: Provide default values for parameters if no argument is passed.
- Keyword arguments: Pass arguments by explicitly specifying the parameter names.
- Variable number of arguments: Use
*argsand**kwargsfor a flexible number of arguments. - Lambda functions: Define small anonymous functions with
lambda. - Function scope: Variables inside a function are local, and those outside are global.
- Docstrings: Add documentation to your functions using docstrings.