Module Reference

This section provides a comprehensive reference for Python modules, detailing their functions, classes, and usage examples. Modules in Python are files containing Python code that can define functions, classes, and variables. They can also include runnable code.

What is a Module?

A module is a Python file (.py) that can be imported into other Python programs. Modules help in organizing and reusing code across different projects. By importing modules, you can access the functions, classes, and variables defined in them.

Commonly Used Python Modules

Here are some of the most commonly used Python modules:

How to Import a Module

To use a module in your Python code, you must first import it using the import statement. For example:

Python
import os

# Now you can use functions from the os module
current_directory = os.getcwd()
print("Current Directory:", current_directory)

Exploring Module Functions

Once you have imported a module, you can explore its functions using the dir() function or by checking the module's documentation. For example:

Python
import math

# List all functions in the math module
print(dir(math))

You can also use the help() function to get detailed information about a module's functions and classes:

Python
help(math)

Creating Your Own Modules

In addition to using built-in modules, you can create your own modules. To create a module, simply save your Python code in a .py file and then import it into other scripts. For example:

Python
# Save this as my_module.py
def greet(name):
    return f"Hello, {name}!"

# Then, in another script, you can import and use it
import my_module

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

By organizing your code into modules, you can make it more modular, reusable, and easier to maintain.