๐ฆ Modules and Packages in Python#
As you build bigger programs, you want to organize your code better and reuse useful pieces easily. Python makes this simple with modules and packagesโbuilding blocks that help you keep your code clean and manageable! Letโs learn how to use them. ๐งฉ
What are Modules? ๐งฑ#
A module is a file containing Python code (functions, classes, variables) that you can reuse by importing it into other programs.
How to Import a Module#
Python comes with many built-in modules you can use right away:
import math
print(math.sqrt(16)) # 4.0
You can also import specific functions or variables:
from math import pi, ceil
print(pi) # 3.141592653589793
print(ceil(4.2)) # 5
Creating Your Own Module ๐ ๏ธ#
Create a file called my_module.py
with the following content:
def greet(name):
return f"Hello, {name}!"
Use this module in another script:
import my_module
print(my_module.greet("Rahul")) # Hello, Rahul!
What are Packages? ๐ฆ#
A package is a folder/directory containing multiple Python modules, organized using a special __init__.py
file.
It helps group related modules together.
my_package/
|-- __init__.py
|-- module1.py
|-- module2.py
You import like this:
from my_package import module1
module1.some_function()
Installing and Using External Packages ๐#
Python has tons of packages you can install via pip (Pythonโs package manager):
pip install requests
Then import and use:
import requests
response = requests.get("https://example.com")
print(response.status_code)
Practice Questions with Solutions ๐#
- Use the built-in
random
module to print a random number between 1 and 10.- Solution:
import random
print(random.randint(1, 10))
- Create a module named
math_utils.py
with a function that returns the factorial of a number. Import and test it. - Create a package with two modules: one with math functions and another with string functions. Experiment with importing them.
Mini Project: Simple Math Module ๐งฎ#
Create a module simple_math.py
:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Use in a separate file:
import simple_math
print(simple_math.add(10, 5)) # 15
print(simple_math.subtract(10, 5)) # 5
Checklist for This Chapter โ #
- Used built-in modules via
import
- Created and imported your own modules
- Understood what packages are and how to import
- Installed and used external packages with pip
Youโre now ready to organize and reuse Python code efficiently! Explore Pythonโs vast ecosystem and even build your own libraries! ๐