Python Basics: Dictionaries, Sets, File Operations, Regular Expressions, Logging, Unit Testing, Profiling, and Third‑Party Libraries
This tutorial introduces core Python concepts—including dictionaries, sets, file and directory handling, regular expressions, logging, unit testing, performance profiling, and common third‑party libraries—providing clear explanations and ready‑to‑run code examples for each topic.
Dictionaries (dict) : A key‑value data structure ideal for storing and retrieving data.
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person["name"]) # Alice
print(person.get("name")) # Alice
person["email"] = "[email protected]" # add
person["age"] = 26 # modify
del person["city"] # delete
for key, value in person.items():
print(f"{key}: {value}")Sets (set) : An unordered collection of unique items, useful for deduplication and set operations.
numbers = {1, 2, 3, 4}
numbers.add(5) # add element
numbers.remove(3) # remove element
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2 # {1, 2, 3, 4, 5}
intersection = set1 & set2 # {3}
difference = set1 - set2 # {1, 2}
symmetric_difference = set1 ^ set2 # {1, 2, 4, 5}File and Directory Operations : Using the os module to manipulate paths, directories, and files.
import os
current_dir = os.getcwd()
print(current_dir)
os.chdir("/path/to/new/directory")
os.mkdir("/path/to/new/directory")
os.rmdir("/path/to/directory")
files = os.listdir("/path/to/directory")
print(files)
path = os.path.join("/home/user", "data", "file.txt")
print(path)
if os.path.exists("/path/to/file.txt"):
print("File exists")
else:
print("File does not exist")
size = os.path.getsize("/path/to/file.txt")
print(size)Regular Expressions : Powerful pattern matching with the re module.
import re
pattern = r"\d+"
text = "The price is 100 dollars."
match = re.search(pattern, text)
if match:
print(match.group()) # 100
new_text = re.sub(r"\d+", "XXX", text)
print(new_text) # The price is XXX dollars.
matches = re.findall(r"\d+", text)
print(matches) # ['100']Logging : Configuring and using the logging module for console and file output.
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
# Log to a file
logging.basicConfig(filename='app.log', level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')Unit Testing : Writing tests with the built‑in unittest framework.
import unittest
def add(a, b):
return a + b
class TestAddition(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
def test_add_negative(self):
self.assertEqual(add(-1, -2), -3)
if __name__ == '__main__':
unittest.main()Performance Profiling : Using cProfile to identify bottlenecks.
import cProfile
def example_function():
# Your code here
pass
cProfile.run('example_function()')Third‑Party Libraries : Installing with pip and using popular packages like requests and beautifulsoup4 .
# Install libraries
pip install requests
pip install beautifulsoup4
# Use requests
import requests
response = requests.get("https://api.example.com/data")
print(response.status_code)
print(response.json())
# Parse HTML with BeautifulSoup
from bs4 import BeautifulSoup
response = requests.get("https://www.example.com")
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.string)Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.