Python Session 04: Functions

Code organization. This session covers function definition, arguments, lambdas, and class structures.

Pre-Session State

  • Understand string methods and f-strings

  • Can use regex patterns

  • Know file I/O

Lesson 1: Function Basics

Concept: Functions encapsulate reusable logic.

Exercise 1.1: Basic function

def greet(name):
    return f"Hello, {name}!"

print(greet("kvm-01"))

Exercise 1.2: Multiple parameters

def format_host(name, ip, vlan=10):
    return f"{name} ({ip}) on VLAN {vlan}"

print(format_host("kvm-01", "10.50.1.110"))
print(format_host("kvm-02", "10.50.1.111", vlan=20))

Exercise 1.3: Return multiple values

def parse_fqdn(fqdn):
    parts = fqdn.split('.', 1)
    return parts[0], parts[1] if len(parts) > 1 else ''

hostname, domain = parse_fqdn("kvm-01.inside.domusdigitalis.dev")
print(f"Host: {hostname}, Domain: {domain}")

Lesson 2: *args and **kwargs

Concept: Handle variable number of arguments.

Exercise 2.1: *args (positional)

def ping_hosts(*hosts):
    for host in hosts:
        print(f"Pinging {host}...")

ping_hosts("kvm-01", "kvm-02", "vault-01")

Exercise 2.2: **kwargs (keyword)

def create_server(**config):
    for key, value in config.items():
        print(f"  {key}: {value}")

create_server(name="kvm-01", ip="10.50.1.110", role="hypervisor")

Exercise 2.3: Combined

def deploy(target, *packages, **options):
    print(f"Deploying to {target}")
    print(f"Packages: {packages}")
    print(f"Options: {options}")

deploy("kvm-01", "nginx", "docker", restart=True, backup=False)

Lesson 3: Lambda Functions

Concept: Anonymous functions for simple operations.

Exercise 3.1: Basic lambda

square = lambda x: x ** 2
print(square(5))  # 25

add = lambda a, b: a + b
print(add(3, 4))  # 7

Exercise 3.2: Lambda with sorted

hosts = [
    {"name": "vault-01", "cpu": 45},
    {"name": "kvm-01", "cpu": 85},
    {"name": "kvm-02", "cpu": 32}
]

by_cpu = sorted(hosts, key=lambda h: h["cpu"], reverse=True)
for h in by_cpu:
    print(f"{h['name']}: {h['cpu']}%")

Exercise 3.3: Lambda with filter/map

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
doubled = list(map(lambda x: x * 2, numbers))
print(evens)    # [2, 4, 6]
print(doubled)  # [2, 4, 6, 8, 10, 12]

Lesson 4: Classes

Concept: Classes group data and behavior.

Exercise 4.1: Basic class

class Server:
    def __init__(self, name, ip):
        self.name = name
        self.ip = ip
        self.active = True

    def ping(self):
        return f"Pinging {self.ip}..."

    def __str__(self):
        return f"Server({self.name}, {self.ip})"

s = Server("kvm-01", "10.50.1.110")
print(s.ping())
print(s)

Exercise 4.2: Class methods

class Server:
    count = 0

    def __init__(self, name):
        self.name = name
        Server.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

    @staticmethod
    def validate_name(name):
        return '-' in name

s1 = Server("kvm-01")
s2 = Server("kvm-02")
print(Server.get_count())  # 2
print(Server.validate_name("kvm-01"))  # True

Lesson 5: Dataclasses

Concept: Simplified class syntax for data containers.

Exercise 5.1: Basic dataclass

from dataclasses import dataclass

@dataclass
class Host:
    name: str
    ip: str
    vlan: int = 10
    active: bool = True

h = Host("kvm-01", "10.50.1.110")
print(h)  # Host(name='kvm-01', ip='10.50.1.110', vlan=10, active=True)
print(h.name)

Exercise 5.2: Dataclass with methods

from dataclasses import dataclass

@dataclass
class Host:
    name: str
    ip: str

    def fqdn(self, domain="inside.domusdigitalis.dev"):
        return f"{self.name}.{domain}"

h = Host("kvm-01", "10.50.1.110")
print(h.fqdn())  # kvm-01.inside.domusdigitalis.dev

Exercise 5.3: Dataclass to dict

from dataclasses import dataclass, asdict
import json

@dataclass
class Host:
    name: str
    ip: str
    vlan: int = 10

h = Host("kvm-01", "10.50.1.110")
d = asdict(h)
print(json.dumps(d, indent=2))

Summary: What You Learned

Concept Syntax Example

Function

def name(args):

def greet(x): return f"Hi {x}"

Default arg

def f(x=val)

def ping(host, port=22)

*args

*args

Tuple of extra positional args

**kwargs

**kwargs

Dict of extra keyword args

Lambda

lambda x: expr

lambda x: x * 2

Class

class Name:

class Server: …​

Dataclass

@dataclass

Auto init, repr

Exercises to Complete

  1. [ ] Write function to validate IP address format

  2. [ ] Create a Host dataclass with ping() method

  3. [ ] Sort list of hosts by IP using lambda

  4. [ ] Write a function accepting **kwargs to build server config

Next Session

Session 05: Subprocess - Running shell commands from Python.

Session Log

Timestamp Notes

Start

<Record when you started>

End

<Record when you finished>