Python Modules

A module in Python is simply a Python file that contains definitions and statements. It can define functions, classes, and variables that you can reference in other Python files, or scripts, using the import statement.

Here's an example of how you can create your own Python module:

  1. Create a Python file - Let's create a Python file named mymodule.py.

# mymodule.py

def greet(name):
    return f"Hello, {name}!"

def add_numbers(a, b):
    return a + b

In this file, we've defined two functions: greet and add_numbers.

  1. Use the module - Now, you can use these functions in another Python file by importing the module.

# main.py

import mymodule

print(mymodule.greet("Alice"))  # prints: Hello, Alice!
print(mymodule.add_numbers(1, 2))  # prints: 3

In main.py, we import mymodule and then call the functions defined in mymodule.py.

Remember, the name of the module is the same as the name of the Python file, but without the .py extension. Also, the Python file that you're importing the module into needs to be in the same directory as the module, or the module needs to be in a directory that's part of the Python path.

Example Module: datetime

The datetime module supplies classes for manipulating dates and times.

Example Module: os

The os module provides a way of using operating system dependent functionality.

Example Module: random

The random module can generate random numbers.

Last updated