Exploring Python: Language, Control Flow, Data Structures, and More

Table of Contents

Language

Control Flow

# Conditionals
x = 10
if x > 0:
    print("positive")
elif x < 0:
    print("negative")
else:
    print("zero")

# Match statement (Python 3.10+)
match command:
    case "start":
        start_server()
    case "stop":
        stop_server()
    case _:
        print("Unknown command")

# Loops
for i in range(5):
    print(i)

while condition:
    do_something()
    if should_stop:
        break

Data Structures

# Lists
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
squares = [x**2 for x in numbers]

# Dictionaries
person = {"name": "Alice", "age": 30}
person["email"] = "alice@example.com"
names = {p["id"]: p["name"] for p in people}

# Sets
unique = {1, 2, 3, 2, 1}  # {1, 2, 3}
a = {1, 2, 3}
b = {2, 3, 4}
a & b  # intersection: {2, 3}
a | b  # union: {1, 2, 3, 4}

# Tuples (immutable)
point = (3, 4)
x, y = point  # unpacking

Error Handling

try:
    result = risky_operation()
except ValueError as e:
    print(f"Value error: {e}")
except (TypeError, KeyError) as e:
    print(f"Error: {e}")
else:
    print("Success!")
finally:
    cleanup()

# Context managers
with open("file.txt") as f:
    content = f.read()

# Custom exceptions
class ValidationError(Exception):
    pass

Classes

from dataclasses import dataclass
from typing import Optional

# Traditional class
class Person:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def greet(self) -> str:
        return f"Hello, I'm {self.name}"

# Dataclass (Python 3.7+)
@dataclass
class User:
    name: str
    email: str
    age: Optional[int] = None

    def is_adult(self) -> bool:
        return self.age is not None and self.age >= 18

Packaging

# pyproject.toml (modern Python packaging)
[project]
name = "mypackage"
version = "0.1.0"
dependencies = [
    "requests>=2.28",
    "pydantic>=2.0",
]

[project.optional-dependencies]
dev = ["pytest", "ruff", "mypy"]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

Development

Environment

# Using uv (fast Python package installer)
uv venv
source .venv/bin/activate
uv pip install -e ".[dev]"

# Or with pip
python -m venv .venv
pip install -e ".[dev]"

Testing

# pytest example
import pytest

def test_addition():
    assert 1 + 1 == 2

@pytest.fixture
def sample_data():
    return {"key": "value"}

def test_with_fixture(sample_data):
    assert sample_data["key"] == "value"

Resources

Author: Jason Walsh

j@wal.sh

Last Updated: 2025-12-21 23:04:24

build: 2025-12-29 20:03 | sha: 3c17632