Functions and Modules

Functions and modules are essential building blocks in Python programming. They help you organize your code, avoid repetition, and make it more readable and reusable.

What is a Function?

A function is a block of code that performs a specific task. You can reuse a function whenever needed instead of writing the same code repeatedly.

Why Use Functions?

  1. Reusability: Write once, use multiple times.
  2. Modularity: Break your code into smaller, logical chunks.
  3. Readability: Makes your code easier to understand.
  4. Maintainability: Easier to update or fix bugs.

Defining a Function

Syntax

Python
Copy
def function_name(parameters):
    """Optional docstring to describe the function."""
    # Function body (code to execute)
    return value  # Optional return value

Example: A Simple Function

Python
Copy
def greet(name):
    """Greets the user with their name."""
    print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!

Key Parts of a Function

  1. def: Starts the function definition.
  2. Function Name: A descriptive name for the function.
  3. Parameters: Inputs the function can accept (optional).
  4. Body: The code inside the function.
  5. Return Statement: Sends a value back to the caller (optional).

Types of Functions

1. Functions Without Parameters

Python
Copy
def say_hello():
    print("Hello, world!")
say_hello()  # Output: Hello, world!

2. Functions With Parameters

Python
Copy
def add(a, b):
    return a + b

result = add(3, 5)  # Output: 8
print(result)

3. Functions With Default Parameters

Python
Copy
def greet(name="Guest"):
    print(f"Welcome, {name}!")

greet()           # Output: Welcome, Guest!
greet("Alice")    # Output: Welcome, Alice!

4. Functions With Variable Arguments Use *args for multiple positional arguments and **kwargs for keyword arguments.

Python
Copy
def print_items(*args):
    for item in args:
        print(item)

print_items(1, 2, 3, "Python")  
# Output: 1, 2, 3, Python


def greet(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

greet(name="Alice", age=25, city="New York")

# Output
# name: Alice
# age: 25
# city: New York

Return Statement

A function can send a value back to where it was called using return.

Example

Python
Copy
def square(number):
    return number * number

result = square(4)
print(result)  # Output: 16

What is a Module?

A module is a file containing Python code (functions, variables, or classes) that you can import and reuse in other programs. Python has many built-in modules, and you can create your own.

Why Use Modules?

  1. Code Organization: Divide code into smaller, logical units.
  2. Reusability: Use the same module in multiple programs.
  3. Built-in Libraries: Access pre-written code for common tasks.

Using Built-in Modules

Python comes with several built-in modules, such as math, random, and datetime.

Importing a Module

You can import a module using the import keyword.

Python
Copy
import math

print(math.sqrt(16))  # Output: 4.0

Import Specific Functions

Python
Copy
from math import sqrt

print(sqrt(25))  # Output: 5.0

Creating Your Own Module

You can create a module by saving Python code in a .py file.

Example

1. Create a file named my_module.py:

Python
Copy
def greet(name):
    print(f"Hello, {name}!")

2. Import and Use the Module:

Python
Copy
import my_module

my_module.greet("Alice")  # Output: Hello, Alice!

Packages

A package is a collection of modules organized into a directory. It typically contains an __init__.py file to initialize the package.

Example:

my_package/ __init__.py module1.py module2.py

You can import modules from the package:

from my_package import module1

Commonly Used Built-in Modules

1. math: For mathematical operations.

Python
Copy
import math
print(math.pi)  # Output: 3.141592653589793

2. random: For generating random numbers.

Python
Copy
import random
print(random.randint(1, 10))  # Random number between 1 and 10

3. datetime: For working with dates and times.

Python
Copy
from datetime import datetime
print(datetime.now())  # Outputs the current date and time

4. os: For interacting with the operating system.

Python
Copy
import os
print(os.getcwd())  # Outputs the current working directory

5. sys: For system-specific parameters and functions.

Python
Copy
import sys
print(sys.version)  # Outputs the Python version

Python Lambda Functions

A lambda function is a small, anonymous function in Python. It is defined using the keyword lambda and can have any number of arguments but only one expression.

Syntax

lambda arguments: expression
  • Arguments: Inputs to the function.
  • Expression: The operation or computation the function performs (automatically returned).

Example

A lambda function to add two numbers:

Python
Copy
add = lambda x, y: x + y
print(add(3, 5))  # Output: 8

Where to Use Lambda Functions?

1. With map(): Apply a function to each item in a list.

Python
Copy
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, numbers))
print(squares)  # Output: [1, 4, 9, 16]

2. With filter(): Filter items from a list.

Python
Copy
numbers = [1, 2, 3, 4]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4]

3. With sorted(): Sort by a custom key.

Python
Copy
words = ["apple", "banana", "cherry"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)  # Output: ['apple', 'cherry', 'banana']

Key Points

  • No name: Lambda functions don’t have a name.
  • One expression: Cannot include multiple statements.
  • Use them for short, simple tasks. For complex logic, use regular functions.