Posts

Mastering Python's decimal Module 💱

Image
Mastering Python's decimal Module 💱 The decimal module enables precise decimal arithmetic without floating-point inaccuracies, essential for financial, scientific, and precise numerical applications. 1. Basic Usage and Creating `Decimal` Objects from decimal import Decimal a = Decimal('0.1') b = Decimal('0.2') print(a + b) # 0.3 (accurate result, unlike float) 2. Rounding and Precision with `getcontext` from decimal import Decimal, getcontext, ROUND_HALF_UP getcontext().prec = 5 # Set total precision to 5 digits getcontext().rounding = ROUND_HALF_UP res = Decimal('1.23456') + Decimal('2.34567') print(res) # 3.5802 (applied precision and rounding) 3. Financial Calculations and Monetary Representation from decimal import Decimal price = Decimal('19.99') quantity = Decimal('3') total = price * quantity print(f"Total amount: {total}") # Total amount: 59.97 4. Comparisons and Precise Division from de...

Python unittest Module: Writing Automated Unit Tests ✅

Image
Python unittest Module: Writing Automated Unit Tests ✅ The unittest module is Python's built-in unit testing framework, essential for verifying the correctness of your code automatically. 1. Writing Simple Function Tests # calc.py def add(a, b): return a + b # test_calc.py import unittest from calc import add class TestCalc(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) self.assertEqual(add(-1, 1), 0) if __name__ == '__main__': unittest.main() 2. Using `setUp()` and `tearDown()` for Common Tasks # test_list.py import unittest class TestList(unittest.TestCase): def setUp(self): self.lst = [1, 2, 3] def tearDown(self): self.lst.clear() def test_append(self): self.lst.append(4) self.assertIn(4, self.lst) def test_pop(self): value = self.lst.pop() self.assertEqual(value, 3) if __name__ == '__main__': unittest.main() 3. Testing ...

Python subprocess Module Explained 🧩

Image
Python subprocess Module Explained 🧩 The subprocess module allows Python scripts to run external commands, scripts, or programs, capturing their output and managing their execution easily and efficiently. 1. Basic Execution with `subprocess.run()` import subprocess result = subprocess.run(['echo', 'Hello World'], capture_output=True, text=True) print(result.stdout) # Hello World 2. Checking Errors and Return Codes import subprocess res = subprocess.run(['ls', 'non_existent_folder'], capture_output=True, text=True) if res.returncode != 0: print("Error:", res.stderr) else: print(res.stdout) 3. Sending Input and Reading Output import subprocess p = subprocess.run(['grep', 'hello'], input='hello world\nhi python', capture_output=True, text=True) print(p.stdout) # hello world 4. Asynchronous Execution with `Popen` import subprocess p = subprocess.Popen(['ping', '-c', '3...

Python's shutil Module Explained 🧰

Image
Python's shutil Module Explained 🧰 The shutil module provides a high-level interface for performing various file and directory operations, such as copying, moving, archiving, and checking disk usage. 1. Copying and Moving Files import shutil # Copy a single file shutil.copy('source.txt', 'dest.txt') # Copy file with metadata shutil.copy2('source.txt', 'backup/source_backup.txt') # Move or rename files shutil.move('old.txt', 'new_folder/renamed.txt') 2. Copying and Removing Directories import shutil # Copy entire directory shutil.copytree('src_folder', 'dst_folder') # Remove entire directory shutil.rmtree('dst_folder') 3. Checking Disk Usage import shutil total, used, free = shutil.disk_usage('/') print(f"Total: {total // (2**30)}GB, Used: {used // (2**30)}GB, Free: {free // (2**30)}GB") 4. Creating and Extracting Archives import shutil # Create zip archive shutil.m...

Getting Started with Python's asyncio ⚡

Image
Getting Started with Python's asyncio ⚡ asyncio is Python’s powerful library for asynchronous programming, enabling efficient handling of network I/O, file operations, and timing-related tasks. 1. Writing Basic Async Functions import asyncio async def say_hello(): print("Hello") await asyncio.sleep(1) print("World") asyncio.run(say_hello()) 2. Executing Multiple Tasks Concurrently import asyncio async def worker(name, delay): await asyncio.sleep(delay) print(f"{name} completed after {delay} seconds") async def main(): tasks = [ worker("Task A", 1), worker("Task B", 2), worker("Task C", 1.5) ] await asyncio.gather(*tasks) asyncio.run(main()) 3. Network I/O Example with aiohttp import asyncio import aiohttp async def fetch(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: print(url, ...

Mastering Python's random Module 🎲

Image
Mastering Python's random Module 🎲 The random module provides versatile tools for generating random numbers, shuffling sequences, sampling, and more. It's widely used for testing, simulations, and probabilistic operations. 1. Generating Random Numbers: uniform, randint, random import random print(random.random()) # float between 0.0 and 1.0 print(random.uniform(10, 20)) # float between 10 and 20 print(random.randint(1, 6)) # integer between 1 and 6 2. Fixing the Seed for Reproducibility import random random.seed(123) print([random.randint(1, 100) for _ in range(5)]) # same results every time 3. Shuffling and Sampling Lists import random arr = list(range(1, 11)) random.shuffle(arr) # shuffle list randomly print(arr) sample = random.sample(arr, 3) # select 3 unique elements print(sample) 4. Weighted and Simple Random Choices import random choices = ['Rock', 'Paper', 'Scissors'] print(random.choice(ch...

Mastering Python's JSON Module 📝

Image
Mastering Python's JSON Module 📝 The json module in Python is essential for converting JSON data to Python objects and vice versa, handling formatting, and managing JSON files seamlessly. 1. JSON String ↔ Python Object import json data = '{"name": "John", "age": 30, "languages": ["Python", "JavaScript"]}' obj = json.loads(data) print(obj, type(obj)) # {'name': 'John', 'age': 30, 'languages': ['Python', 'JavaScript']} s = json.dumps(obj) print(s, type(s)) # String 2. Pretty Printing with Indentation import json obj = {"name": "Jane", "age": 25, "city": "New York"} pretty = json.dumps(obj, indent=4, ensure_ascii=False) print(pretty) # { # "name": "Jane", # "age": 25, # "city": "New York" # } 3. Reading and Writing JSON Files import json...