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