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  # Optional

Example:

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 return statement 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:

  1. Positional Parameters: Must be provided in the order they appear in the function definition.

  2. Default Parameters: Provide default values for arguments, making them optional.

  3. Keyword Arguments: Allow specifying arguments by name, regardless of their order.

  4. Arbitrary Arguments: Use *args for non-keyword variable-length arguments and **kwargs for 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:

  1. Local Scope: Variables declared inside a function are accessible only within that function.

  2. Global Scope: Variables declared outside all functions are accessible everywhere.

  3. 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(), and reduce().

Higher-Order Functions

Functions that accept other functions as arguments or return them as results are called higher-order functions.

Examples:

Best Practices

  1. Use meaningful names for functions and parameters.

  2. Keep functions short and focused on a single task.

  3. Document functions with docstrings.

  4. Avoid using global variables; prefer passing arguments to functions.

  5. 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