Modules in Python
A module is a file that contains Python code such as functions, variables, and classes. Modules help you organize and reuse code efficiently.
💡 Python modules allow you to write code once and
use it anywhere.
Using Built-in Modules
Python comes with many built-in modules like
math, random, and datetime.
import math
print(math.sqrt(25))
print(math.pi)
Different Ways to Import Modules
1. Import entire module
import random
print(random.randint(1, 10))
2. Import specific items
from math import sqrt, pi
print(sqrt(16))
print(pi)
3. Import with alias
import datetime as dt
print(dt.date.today())
Creating Your Own Module
You can create your own module by saving Python code in a .py file.
# file: calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Using your custom module:
import calculator
print(calculator.add(5, 3))
print(calculator.subtract(10, 4))
Exploring Modules
Use dir() and help() to explore module contents.
import math
print(dir(math))
help(math)
Practice Exercises
- Use the
randommodule to generate a number between 1 and 100 - Import only
sqrtfrom the math module - Create a module that converts Celsius to Fahrenheit