Python's rich ecosystem of modules empowers developers to harness a wide range of functionalities without reinventing the wheel. In this post, we'll dive into the world of Python modules, including custom ones, and showcase some common modules with practical examples.
import math print(math.sqrt(25)) # Output: 5.0
from datetime import datetime today = datetime.today() print(today.strftime("%Y-%m-%d %H:%M:%S")) # Output: 2023-09-26 14:30:00
import random random_num = random.randint(1, 100) print(random_num)
import os current_dir = os.getcwd() print(current_dir)
import json data = {"name": "John", "age": 30} json_str = json.dumps(data)
You can create your own modules to encapsulate code for reuse across projects. Let's create a simple custom module called `myutils.py`.
# myutils.py def greet(name): return f"Hello, {name}!" def add(a, b): return a + b
Now, let's use this custom module in another script:
# main.py import myutils message = myutils.greet("Alice") sum_result = myutils.add(5, 3) print(message) # Output: Hello, Alice! print(sum_result) # Output: 8
import requests response = requests.get("https://www.example.com") print(response.status_code)
import numpy as np arr = np.array([1, 2, 3]) mean = np.mean(arr)
import pandas as pd data = {"Name": ["Alice", "Bob"], "Age": [25, 30]} df = pd.DataFrame(data)
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [10, 15, 7, 12] plt.plot(x, y) plt.show()
Python's module ecosystem is vast and versatile. Whether you're building web applications, doing data analysis, or working on scientific projects, Python modules offer a treasure trove of tools to make your life easier. So, explore, experiment, and harness the power of Python modules in your projects! 💪🐍
#Python #Programming #Modules #CustomModules #Examples