Chapter 4: Functions
Functions are reusable blocks of code designed to perform a specific task. They help organize code, reduce repetition, and improve readability and maintainability. In Python, functions are first-class objects, meaning they can be passed around as arguments, returned from other functions, and assigned to variables.
Defining and Calling Functions
A function must be defined before it can be called. Use the def keyword to define a function. Functions can take inputs, perform tasks, and optionally return outputs.
Syntax:
def function_name(parameters):
"""Optional documentation string (docstring)"""
# Code block
return value # OptionalExample:
def greet(name):
"""This function returns a greeting message."""
return f"Hello, {name}!"
# Calling the function
greeting = greet("Alice")
print(greeting)Key Points:
Function names should follow the same naming rules as variables.
Parameters are optional; a function can take zero or more arguments.
The
returnstatement is optional but allows the function to send a result back to the caller.Include a docstring to describe the function’s purpose and behavior.
Parameters and Arguments
Types of Parameters:
Positional Parameters: Must be provided in the order they appear in the function definition.
Default Parameters: Provide default values for arguments, making them optional.
Keyword Arguments: Allow specifying arguments by name, regardless of their order.
Arbitrary Arguments: Use
*argsfor non-keyword variable-length arguments and**kwargsfor keyword variable-length arguments.
Return Values
A function can return a value to the caller using the return statement. If no return is provided, the function implicitly returns None.
Examples:
Scope and Lifetime of Variables
Scope determines where a variable can be accessed, while lifetime refers to how long it exists.
Types of Scope:
Local Scope: Variables declared inside a function are accessible only within that function.
Global Scope: Variables declared outside all functions are accessible everywhere.
Global Keyword: Used to modify a global variable inside a function.
Lifetime:
Local variables are destroyed when the function execution ends.
Global variables persist throughout the program’s execution.
Lambda Functions
Lambda functions are anonymous, single-line functions defined using the lambda keyword. They are useful for short, simple operations.
Syntax:
Examples:
Key Points:
Lambda functions can have multiple arguments but only one expression.
They are often used with higher-order functions like
map(),filter(), andreduce().
Higher-Order Functions
Functions that accept other functions as arguments or return them as results are called higher-order functions.
Examples:
Best Practices
Use meaningful names for functions and parameters.
Keep functions short and focused on a single task.
Document functions with docstrings.
Avoid using global variables; prefer passing arguments to functions.
Test functions independently.
Exercises
Exercise 1:
Write a function that calculates the greatest common divisor (GCD) of two numbers.
Solution:
Exercise 2:
Write a function to generate the Fibonacci sequence up to a given number n.
Solution:
Exercise 3:
Write a function that accepts another function as an argument and applies it to a list of numbers.
Solution:
In the next chapter, we will explore Python’s data structures, including lists, tuples, dictionaries, and sets.
Last updated