Introduction
A module in Python is like a toolbox full of functions, classes, and variables that you can reuse in your programs. Instead of writing the same code over and over again, you can store it in a module and import it whenever needed. Think of it like ordering pizza instead of making it from scratch every time!
Creating a Module
A module is just a Python file that contains functions and variables.
Let's create a simple module called mymodule.py
:
# mymodule.py
def greet(name):
return f"Hello, {name}! Welcome to Python."
pi = 3.14159
This module contains a function greet()
and a variable pi
. Now, we can import and use it!
Importing a Module
To use a module, simply import it into your script:
import mymodule
print(mymodule.greet("Alice")) # Hello, Alice! Welcome to Python.
print(mymodule.pi) # 3.14159
Importing Specific Items
If you only need specific functions or variables, use:
from mymodule import greet
print(greet("Bob")) # Hello, Bob! Welcome to Python.
Now, you don’t need to prefix greet
with mymodule.
Renaming a Module
You can rename a module while importing it using as
:
import mymodule as mm
print(mm.greet("Charlie"))
Built-in Modules
Python comes with many built-in modules like math
, random
, and datetime
.
import math
print(math.sqrt(25)) # 5.0
Checking Available Functions
Use dir(module_name)
to see what a module contains:
import math
print(dir(math)) # Shows all functions inside math module
Where to Store Modules?
Python looks for modules in these places:
- The same directory as your script
- The system-wide Python library folder
- Locations listed in
sys.path
To check Python’s module search paths:
import sys
print(sys.path)
Installing External Modules
Want to use third-party modules? Install them with pip:
pip install requests
Then, import it like a normal module:
import requests
print(requests.get("https://www.python.org"))
Summary
Concept | Description |
---|---|
Module | A Python file containing reusable code |
import module_name |
Imports the entire module |
from module import X |
Imports a specific function/variable |
import module as alias |
Renames a module during import |
sys.path |
Shows Python's module search locations |
pip install module |
Installs third-party modules |
Modules make Python programming cleaner, reusable, and more efficient!
0 Comments