Drill 01: Fundamentals

Types, lists, dicts, sets, and comprehensions. The foundation of Python.

Run This Drill

bash ~/atelier/_bibliotheca/domus-captures/docs/modules/ROOT/examples/python-drills/01-fundamentals.sh

Drill Script

#!/bin/bash
# PYTHON DRILL 01: FUNDAMENTALS
# Paste this entire script into your terminal
# Topics: Types, data structures, comprehensions

echo "=================================================================="
echo "             PYTHON DRILL 01: FUNDAMENTALS                       "
echo "=================================================================="
echo ""

# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.1: BASIC TYPES"
echo "int, float, str, bool"
echo "------------------------------------------------------------------"
echo ""
python3 << 'PYEOF'
# Integer operations
port = 443
vlan = 10
print(f"Port: {port}, VLAN: {vlan}")
print(f"Sum: {port + vlan}, Product: {port * vlan}")

# Float
latency = 45.7
print(f"Latency: {latency}ms, Rounded: {round(latency)}")

# String
hostname = "ise-01"
domain = "inside.domusdigitalis.dev"
fqdn = f"{hostname}.{domain}"
print(f"FQDN: {fqdn}")
print(f"Upper: {hostname.upper()}, Length: {len(fqdn)}")

# Boolean
enabled = True
status = "active"
is_active = enabled and status == "active"
print(f"Is active: {is_active}")
PYEOF
echo ""

# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.2: LISTS"
echo "Ordered, mutable sequences"
echo "------------------------------------------------------------------"
echo ""
python3 << 'PYEOF'
# Creating lists
hosts = ["ise-01", "ise-02", "bind-01"]
print(f"Hosts: {hosts}")
print(f"First: {hosts[0]}, Last: {hosts[-1]}")
print(f"Length: {len(hosts)}")

# Slicing
print(f"First two: {hosts[:2]}")
print(f"Reversed: {hosts[::-1]}")

# Modifying
hosts.append("vault-01")
print(f"After append: {hosts}")

hosts.insert(0, "gateway")
print(f"After insert: {hosts}")

removed = hosts.pop()
print(f"Removed: {removed}, Now: {hosts}")

# Checking membership
print(f"'ise-01' in hosts: {'ise-01' in hosts}")
PYEOF
echo ""

# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.3: DICTIONARIES"
echo "Key-value pairs - the most important data structure"
echo "------------------------------------------------------------------"
echo ""
python3 << 'PYEOF'
# Creating dicts
server = {
    "hostname": "ise-01",
    "ip": "10.50.1.20",
    "port": 443,
    "roles": ["pan", "mnt", "psn"]
}
print(f"Server: {server}")
print(f"Hostname: {server['hostname']}")
print(f"IP: {server.get('ip')}")
print(f"Missing key: {server.get('missing', 'default')}")

# Modifying
server["status"] = "active"
server["port"] = 8443
print(f"Updated: {server}")

# Iterating
print("\nKeys:")
for key in server.keys():
    print(f"  {key}")

print("\nKey-Value pairs:")
for key, value in server.items():
    print(f"  {key}: {value}")
PYEOF
echo ""

# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.4: LIST COMPREHENSIONS"
echo "Concise list creation"
echo "------------------------------------------------------------------"
echo ""
python3 << 'PYEOF'
# Basic comprehension
vlans = [10, 20, 30, 50, 99]
doubled = [v * 2 for v in vlans]
print(f"Doubled VLANs: {doubled}")

# With condition
high_vlans = [v for v in vlans if v > 25]
print(f"VLANs > 25: {high_vlans}")

# Transform strings
hosts = ["ise-01", "ise-02", "bind-01"]
fqdns = [f"{h}.example.com" for h in hosts]
print(f"FQDNs: {fqdns}")

# Filter and transform
ise_hosts = [h.upper() for h in hosts if h.startswith("ise")]
print(f"ISE hosts (upper): {ise_hosts}")

# Nested
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]
print(f"Flattened: {flat}")
PYEOF
echo ""

# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.5: DICT COMPREHENSIONS"
echo "Build dicts efficiently"
echo "------------------------------------------------------------------"
echo ""
python3 << 'PYEOF'
# Basic dict comprehension
hosts = ["ise-01", "bind-01", "vault-01"]
host_lengths = {h: len(h) for h in hosts}
print(f"Lengths: {host_lengths}")

# With enumerate for index
host_ids = {h: i for i, h in enumerate(hosts, start=1)}
print(f"IDs: {host_ids}")

# From two lists
names = ["web", "db", "cache"]
ports = [80, 5432, 6379]
services = {name: port for name, port in zip(names, ports)}
print(f"Services: {services}")

# Filtering
active = {"web": True, "db": True, "cache": False}
running = {k: v for k, v in active.items() if v}
print(f"Running: {running}")
PYEOF
echo ""

# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.6: SETS"
echo "Unique values, fast membership testing"
echo "------------------------------------------------------------------"
echo ""
python3 << 'PYEOF'
# Creating sets
vlans1 = {10, 20, 30}
vlans2 = {20, 30, 40, 50}

print(f"Set 1: {vlans1}")
print(f"Set 2: {vlans2}")

# Set operations
print(f"Union: {vlans1 | vlans2}")
print(f"Intersection: {vlans1 & vlans2}")
print(f"Difference (1-2): {vlans1 - vlans2}")
print(f"Symmetric diff: {vlans1 ^ vlans2}")

# From list (dedup)
ips = ["10.50.1.20", "10.50.1.21", "10.50.1.20", "10.50.1.22"]
unique_ips = set(ips)
print(f"Unique IPs: {unique_ips}")
PYEOF
echo ""

# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "YOUR TURN - TYPE THESE IN PYTHON REPL:"
echo "------------------------------------------------------------------"
echo ""
echo "1. Create a list of 5 server names, get the middle 3:"
echo "   servers = ['web-01', 'web-02', 'db-01', 'cache-01', 'api-01']"
echo "   middle = servers[1:4]"
echo ""
echo "2. Build a dict of {hostname: ip} for 3 servers:"
echo "   inventory = {'ise-01': '10.50.1.20', 'bind-01': '10.50.1.90'}"
echo ""
echo "3. List comprehension - extract IPs ending in .20:"
echo "   ips = ['10.50.1.20', '10.50.1.21', '10.50.1.30']"
echo "   filtered = [ip for ip in ips if ip.endswith('.20')]"
echo ""
echo "------------------------------------------------------------------"
echo "KEY TAKEAWAYS:"
echo "1. f-strings for formatting: f\"{var}\""
echo "2. Lists are mutable, ordered: [1, 2, 3]"
echo "3. Dicts for key-value: {'key': 'value'}"
echo "4. Comprehensions: [x for x in items if cond]"
echo "5. Sets for unique values: {1, 2, 3}"
echo "------------------------------------------------------------------"