Python modules are files containing Python code (functions, classes, and variables) that can be imported and reused in other programs. They help keep code organized, reusable, and efficient.
Python modules are categorized into three main types:
os
, sys
, math
, random
, datetime
, json
, etc.import math
print(math.sqrt(16)) # Output: 4.0
.py
file.# my_module.py
def greet(name):
return f"Hello, {name}!"
Import and use it in another script:
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
pip
and not included in Python by default.numpy
, pandas
, requests
, flask
, etc.pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # Output: 200
Here are some commonly used built-in Python modules:
Module | Purpose |
---|---|
os |
Interact with the operating system (files, directories, environment variables) |
sys |
Access system-specific parameters & functions |
math |
Perform mathematical operations |
random |
Generate random numbers |
datetime |
Work with dates and time |
time |
Handle time-related functions |
json |
Parse and handle JSON data |
re |
Work with regular expressions |
statistics |
Perform statistical operations |
csv |
Read and write CSV files |
To see a list of available modules in Python:
help('modules')
import math
print(math.pi) # Output: 3.141592653589793
2. Import specific functions
from math import sqrt, ceil
print(sqrt(25)) # Output: 5.0
print(ceil(4.3)) # Output: 5
3. Import with an alias
import datetime as dt
print(dt.datetime.now()) # Current date and time
4. Import everything using
from math import *
print(factorial(5)) # Output: 120
Create a file my_module.py with some functions:
# my_module.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Step 2: Import and use it
import my_module
print(my_module.add(5, 3)) # Output: 8
print(my_module.subtract(10, 4)) # Output: 6
To check where Python imports a module from:
import math
print(math.__file__)
✔ Python modules make code reusable and organized.
✔ There are built-in, user-defined, and external modules.
✔ You can import modules in different ways using import
, from module import
, or aliases.
✔ External modules can be installed via pip install module_name
.
Scope @ NareshIT:
At NareshIT’s Python application Development program you will be able to get the extensive hands-on training in front-end, middleware, and back-end technology.
It skilled you along with phase-end and capstone projects based on real business scenarios.
Here you learn the concepts from leading industry experts with content structured to ensure industrial relevance.
An end-to-end application with exciting features
Course :