Introduction to Python Modules

A module in Python is a file that contains Python code, typically including functions, classes, and variables. Modules help organize and reuse code efficiently.


1. What is a Python Module?

A module is simply a .py file containing reusable code. Python provides built-in modules, and you can also create custom modules.

Example of a Simple Module:

Create a file mymodule.py with the following code:

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

Now, import and use it in another Python file:

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

2. Importing Modules

Python provides multiple ways to import modules:

  • import module_name – Imports the whole module.
  • from module_name import function_name – Imports specific functions or variables.
  • import module_name as alias – Imports with an alias.
  • from module_name import * – Imports everything (not recommended).

Example:

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

from math import pi
print(pi)  # Output: 3.141592653589793

import math as m
print(m.factorial(5))  # Output: 120

3. Built-in Python Modules

Python has many built-in modules, such as:

  • math – Mathematical functions
  • random – Generating random numbers
  • datetime – Handling dates and times
  • os – Interacting with the operating system
  • sys – System-specific parameters and functions

Example of Using random Module:

import random
print(random.randint(1, 10))  # Generate a random number between 1 and 10

4. Creating and Using Custom Modules

You can create your own module by saving Python functions in a .py file and importing them.

Example:

Create calculator.py with:

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

Now, use it in another file:

import calculator
print(calculator.add(5, 3))  # Output: 8

5. The __name__ Variable in Modules

When a Python script runs, the __name__ variable determines if the script is being run directly or imported.

Example:

if __name__ == "__main__":
    print("This script is run directly!")
else:
    print("This script is imported as a module.")

6. The dir() Function

The dir() function lists all attributes and methods of a module.

Example:

import math
print(dir(math))

7. Installing External Modules using pip

Python allows installing third-party modules using pip, the package manager.

Example:

pip install requests

Now, use the installed module:

import requests
response = requests.get("https://www.example.com")
print(response.status_code)

8. Summary

Modules help organize and reuse Python code efficiently.
Built-in modules like math, random, and os simplify complex tasks.
Custom modules allow the creation of reusable functions.
The __name__ variable differentiates between script execution and module import.
External modules can be installed via pip.

SRIRAM
SRIRAM

Sriram is a seasoned Computer Science educator and mentor. He is UGC NET Qualified twice (2014 & 2019) and holds State Eligibility Test (SET) qualifications for both Andhra Pradesh (AP) and Telangana (TG). With years of experience teaching programming languages, he simplifies complex CS concepts for aspirants of UGC NET Computer Science, KVS, NVS, EMRS, and other competitive exams.