Functions in Python are reusable blocks of code that perform a specific task. They allow you to break your code into smaller, manageable parts, make your code modular, and promote code reusability.
5.1 Defining a Function
In Python, a function is defined using the def keyword followed by the function name and parentheses (). You can also include parameters within the parentheses. Here's the basic structure of a Python function:
# Example of a simple function
def greet():
print("Hello, welcome to Python!")
To call a function, simply write its name followed by parentheses:
# Calling a function
greet()
5.2 Function Arguments
Functions can take arguments (also called parameters) that allow you to pass data to the function.
# Function with arguments
def greet(name):
print(f"Hello, {name}!")
# Calling the function with an argument
greet("Alice")
5.2.1 Positional Arguments
Arguments that are passed to a function in the correct positional order are called positional arguments.
# Function with multiple positional arguments
def add_numbers(a, b):
return a + b
# Calling the function with positional arguments
result = add_numbers(3, 5)
print(result)
5.2.2 Keyword Arguments
You can also pass arguments using the name of the parameter. These are called keyword arguments, and their order does not matter.
# Using keyword arguments
def greet_user(name, age):
print(f"Name: {name}, Age: {age}")
greet_user(name="Alice", age=25)
greet_user(age=30, name="Bob")
5.2.3 Default Arguments
You can define default values for parameters in a function. If no argument is provided, the default value is used.
# Function with default arguments
def greet(name="Guest"):
print(f"Hello, {name}!")
# Calling the function without an argument
greet()
# Calling the function with an argument
greet("Alice")
5.3 Return Values
Functions can return values using the return statement. This allows you to send a result back to the caller.
# Function with a return value
def add_numbers(a, b):
return a + b
# Capture the return value in a variable
result = add_numbers(10, 5)
print(result)
5.4 Variable Scope
In Python, variables inside a function are called local variables, and they are only accessible within that function. Variables defined outside a function are global variables and can be accessed by any part of the program.
5.4.1 Local Variables
# Local variable example
def my_function():
x = 10 # Local variable
print(x)
my_function()
# Trying to access local variable outside the function will cause an error
# print(x) # Uncommenting this line will raise a NameError
5.4.2 Global Variables
# Global variable example
x = 5 # Global variable
def my_function():
print(x)
my_function()
print(x)
5.4.3 Using global Keyword
If you want to modify a global variable inside a function, you can use the global keyword.
# Using the global keyword
x = 5
def my_function():
global x
x = 10 # Modifies the global variable
my_function()
print(x) # Outputs 10
5.5 Lambda Functions
Lambda functions are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression. Lambda functions are often used for short, simple operations.
# Example of a lambda function
add = lambda a, b: a + b
# Using the lambda function
result = add(3, 5)
print(result)
5.6 Recursion
Recursion is a technique where a function calls itself. It's often used to solve problems that can be broken down into smaller, similar subproblems. Be careful when using recursion to ensure you include a base case to prevent infinite loops.
# Example of a recursive function
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
# Calling the recursive function
print(factorial(5)) # Outputs 120
Comments
Post a Comment