Defining Functions

Functions are reusable blocks of code that perform a specific task. They are defined using the def keyword, followed by the function name, parentheses for parameters, and a colon. The function body is indented with a consistent indentation style (usually 4 spaces).

def greet(name):
print(f"Hello, {name}!")
greet("Alice")  # Output: Hello, Alice!

Function Parameters

Parameters are values that are passed into a function when it is called. They allow you to provide input data to the function, which can be used within the function body.

def add_numbers(x, y):
result = x + y
return result
sum = add_numbers(3, 5)
print(sum)  # Output: 8

Return Statement

The return statement is used to return a value from a function. If no return statement is present, the function will return None by default.

def multiply(a, b):
product = a * b
return product
result = multiply(4, 6)
print(result)  # Output: 24

Scope of Variables

Variables in Python have different scopes: local, global, and built-in. Local variables are defined inside a function and are only accessible within that function. Global variables are defined outside of any function and can be accessed throughout the program. Built-in variables are part of the Python interpreter and are always available.

x = 10  # Global variable
def my_function():
y = 5  # Local variable
print(x)  # Accessing a global variable
print(y)
my_function()  # Output: 10, 5

Lambda Functions

Lambda functions, also known as anonymous functions, are small, one-line functions that can have any number of arguments but can only have a single expression. They are typically used in situations where a simple function is needed for a short period of time.

square = lambda x: x ** 2
result = square(5)
print(result)  # Output: 25

Recursive Functions

Recursive functions are functions that call themselves with a different set of parameters until a base case is reached. They are often used to solve problems that can be broken down into smaller instances of the same problem.

def factorial(n):
if n == 0:
    return 1
else:
    return n * factorial(n - 1)
print(factorial(5))  # Output: 120

In the next chapter, we'll explore modules and packages in Python, which are essential for organizing and reusing code across different parts of a project or multiple projects.