Python Modules Tutorial
A module in Python is a file containing Python code — functions, classes, and variables — that can be imported and reused in different programs. Modules help organize code, improve reusability, and keep things clean and modular! Let’s break it down.
🌟 1. Importing Modules
To use a module, we use the import
keyword.
✅ Import the entire module:
import math
print(math.sqrt(25)) # Output: 5.0
✅ Import a specific function:
from math import sqrt
print(sqrt(36)) # Output: 6.0
✅ Import a module with an alias:
import math as m
print(m.pi) # Output: 3.141592653589793
🔍 2. Built-in Python Modules
Python provides a rich set of standard libraries. Let’s look at some popular ones!
✨ Math Module (math)
import math
print(math.factorial(5)) # Output: 120
print(math.pow(2, 3)) # Output: 8.0
print(math.pi) # Output: 3.141592653589793
✨ Random Module (random)
import random
print(random.randint(1, 10)) # Random number between 1 and 10
print(random.choice(['apple', 'banana', 'cherry'])) # Random choice
✨ Datetime Module (datetime)
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # Current date and time
🧑🍳 3. Creating Your Own Python Module
You can create your own module by saving Python code in a .py
file.
✅ mymodule.py
def greet(name):
return f"Hello, {name}!"
✅ Using the custom module:
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
✅ Ensure the .py
file is in the same directory as your script.
🏷️ 4. Finding Installed Modules
You can see a list of installed modules with:
help("modules")
🔐 5. Packages (Multiple Modules)
A package is a collection of modules organized into directories with an __init__.py
file.
✅ Folder structure:
my_package/
│
├── __init__.py
├── module1.py
├── module2.py
✅ Using the package:
from my_package import module1, module2
🚀 Conclusion
- Modules help you write reusable, organized code.
- Use built-in modules for common tasks and create custom ones for modular projects!
- Once you master Python modules, you’re well on your way to building powerful, maintainable applications.
✨ Let me know if you’d like to dive deeper into a specific Python module! 🚀
0 comments:
Post a Comment