Python Modules

🐍 Python Modules

A module in Python is simply a file that contains Python code — such as variables, functions, classes, etc.

Modules help in:

 Code reusability
 Better organization
 Avoiding duplication
 Working with built-in tools


 1. Using Built-in Modules

Python comes with many modules like:
math, random, datetime, os, etc.

Example:


 


 2. import Statement

There are multiple ways to import modules:

 whole module

 specific function

  module with alias

  multiple functions


 3. Create Your Own Module

Create a file named: my_module.py

def greet(name):
return f"Hello {name}, welcome!"
pi = 3.14

Now import it in another file:

import my_module

print(my_module.greet(“Vipul”))
print(my_module.pi)


 4. Using from module import *

This imports everything from a module:

⚠ Not recommended for large projects because it becomes unclear what came from where.


 5. Built-in Useful Modules

Module Name Purpose
math Mathematical operations
random Generate random numbers
datetime Work with dates/time
os Operating system interaction
sys System-specific functions
statistics Mean, median, mode

Examples

📌 Random Module


 

📌 Datetime Module


 


 6. Check What’s Inside a Module

Use the dir() function:


 7. Working with Packages

A package is a group of modules stored in a folder containing an __init__.py file.

Example:

myproject/
└── utilities/
├── __init__.py
├── math_utils.py
└── string_utils.py

Usage:

from utilities.math_utils import add

 8. Install External Modules (PIP)

Use terminal command:

pip install numpy

Then import and use:


 


📌 Summary Table

Import Type Example
Import whole module import math
Import with alias import math as m
Import function from math import sqrt
Import all from math import *
Custom module import my_module

🧠 Practice Tasks

  1. Create a module named calculator.py with add, subtract, multiply, divide functions and import it.

  2. Use the random module to create a dice rolling program.

  3. Use datetime to print a user-friendly timestamp.

  4. Install an external package like pyjokes and print a random joke.

You may also like...