Platform Engineering · Lesson 34

Python Fundamentals: Types, Collections, and Control Flow

Most DevOps scripts do the same few things: read some values, compare them, group them, and act on the ones that match. In Python that means variables and types (strings, numbers, booleans, None), the four built-in collections (list, tuple, dict, set), and control flow (if, for, while, comprehensions). This lesson builds one disk-alert script from those pieces, and shows the two beginner mistakes that make it alert on the wrong hosts: comparing numbers as text, and copying a list with =.

Difficulty: Beginner · Know this first: Lesson 28, Lesson F04

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up developer minutes to write the script and trust its output. It is a worked example, not a measurement. The numbers and lists hops are where a script runs without errors and still gives the wrong answer.

Try it: string comparison or number comparison?

Pick a disk percentage and the threshold, and see what Python says when they are compared as strings and as numbers.

True"pct" > "limit" as strings
Falsepct > limit as numbers

They disagree: the string comparison would raise a false alarm

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Python fundamentals grow in four levels: values and types, collections, idiomatic control flow, and the object model behind it all.

Basic — Values, types, and printing

At the basic level you can store, convert, and print values.

  • str, int, float, bool, None; type(), int("8"), str(8).
  • f-strings: f"{name} has {n:,} files ({pct:.1f}%)".
  • Arithmetic: / always gives a float, // floors, % is the remainder, ** is a power.

Where it breaks: "5" + 3 is a TypeError; Python does not convert for you.

Try it: Basic

What is 7 / 2 in Python 3?

Now do it: Try 7 / 2, 7 // 2, and 7 % 2 in python3.

Intermediate — Collections

At the intermediate level you pick the right collection.

  • list (ordered, changeable), tuple (fixed record), dict (lookup by key), set (unique, membership).
  • Copying: .copy() is shallow; copy.deepcopy() for nested structures.
  • collections.Counter, defaultdict, namedtuple.

Try it: Intermediate

You need a count of how many times each error appears in a log. What fits best?

Now do it: Count words in a file with Counter and print the top five.

Advanced — Idiomatic control flow

At the advanced level code is short and clear.

  • Comprehensions for lists, dicts, and sets; any(), all(), sum(), sorted(key=...).
  • for ... else, break, continue; match statements for structured data.
  • Unpacking: first, *rest = items; zip() to walk two lists together.

Try it: Advanced

What does any(p >= 95 for p in usage.values()) return?

Now do it: Rewrite a loop that sets a flag as one any() call.

Master — Names, objects, and mutability

At the master level you reason about the object model.

  • Names point to objects; is compares identity, == compares value.
  • Mutable (list, dict, set) versus immutable (int, str, tuple, frozenset); why dict keys must be hashable.
  • Big-O of common operations: list append O(1), list membership O(n), dict and set lookup O(1) on average.

Trade-off: mutating in place saves memory and surprises other code holding the same object; returning new objects is safer and costs a copy.

Try it: Master

Why can a tuple be a dict key but a list cannot?

Now do it: Try {[1, 2]: "x"} and read the error.

Go deeper

The complete disk-alert script. Save it as disk_alert.py and run it on any Linux machine.

#!/usr/bin/env python3
"""Alert on file systems above a threshold, using only the standard library."""
import subprocess
import sys

WARN, CRIT = 85, 95
MUTED = {"/boot/efi"}

out = subprocess.run(["df", "-P"], capture_output=True, text=True, check=True).stdout
usage = {}
for line in out.splitlines()[1:]:          # skip the header
    fields = line.split()
    mount, pct = fields[5], int(fields[4].rstrip("%"))   # convert early
    usage[mount] = pct

alerts = []
for mount, pct in sorted(usage.items(), key=lambda kv: kv[1], reverse=True):
    if mount in MUTED:
        continue
    if pct >= CRIT:
        alerts.append(("critical", mount, pct))
    elif pct >= WARN:
        alerts.append(("warning", mount, pct))

for level, mount, pct in alerts:
    print(f"{level:<8} {pct:>3}%  {mount}")
print(f"{len(usage)} file systems checked, {len(alerts)} over {WARN}%", file=sys.stderr)
sys.exit(1 if alerts else 0)

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A disk check that ran every five minutes for a year missed every full disk.

Timeline

  • Year 0A script compares df percentages with "85" as strings. It works in testing because the test disks were at 86 and 90 percent.
  • Year 1A log volume reaches 100 percent overnight. "100" > "85" is False, so no alert fires. The API stops writing at 03:10.
  • Year 1, +1 hThe bug is found by reading the script; int() fixes it in one line.

What changed after

Values are converted where they are read, the script has a test with 9, 85, 86, and 100 percent, and scripts that check thresholds go through code review.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. The raw input a script reads: df output, one line per file system.

    df -P | head -4
  2. Strings compare letter by letter, numbers by value.

    python3 -c "print('9' > '85', 9 > 85, '100' > '85', 100 > 85)"
  3. = shares a list; .copy() makes a new one.

    python3 -c "a = [1, 2]; b = a; b.append(3); c = a.copy(); c.append(4); print(a, b, c, b is a)"
  4. A one-line disk check: convert, compare, comprehend.

    df -P | python3 -c "import sys; rows = [l.split() for l in sys.stdin][1:]; print([(r[5], int(r[4][:-1])) for r in rows if int(r[4][:-1]) >= 50])"

2. Python: disk_types.py

This program runs the same disk check twice: once comparing percentages as strings, once as numbers, and shows exactly which hosts each version alerts on. Save it as disk_types.py, then run it.

# disk_types.py
df_lines = ["web1 86%", "app3 9%", "db1 100%", "cache 40%", "web2 91%", "log1 85%"]
THRESHOLD = "85"

as_text = [line.split()[0] for line in df_lines if line.split()[1].rstrip("%") > THRESHOLD]
as_numbers = [line.split()[0] for line in df_lines if int(line.split()[1].rstrip("%")) > int(THRESHOLD)]
print("compared as strings:", sorted(as_text))
print("compared as numbers:", sorted(as_numbers))
print("false alarms:", sorted(set(as_text) - set(as_numbers)), "missed:", sorted(set(as_numbers) - set(as_text)))

production = ["web1", "web2", "db1"]
staging = production          # not a copy
staging.clear()
staging += ["stg1"]
print("production after editing 'staging':", production)

Run it, and you should see this output:

$ python3 disk_types.py
compared as strings: ['app3', 'web1', 'web2']
compared as numbers: ['db1', 'web1', 'web2']
false alarms: ['app3'] missed: ['db1']
production after editing 'staging': ['stg1']

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-core-types-collections-and-control-flow && cd ~/labs/python-core-types-collections-and-control-flow) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Python Fundamentals: Types, Collections, and Control Flow", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'The raw input a script reads: df output, one line per file system.'
  'Strings compare letter by letter, numbers by value.'
  '= shares a list; .copy() makes a new one.'
  'A one-line disk check: convert, compare, comprehend.'
)

step_1() {
df -P | head -4
}

step_2() {
python3 -c "print('9' > '85', 9 > 85, '100' > '85', 100 > 85)"
}

step_3() {
python3 -c "a = [1, 2]; b = a; b.append(3); c = a.copy(); c.append(4); print(a, b, c, b is a)"
}

step_4() {
df -P | python3 -c "import sys; rows = [l.split() for l in sys.stdin][1:]; print([(r[5], int(r[4][:-1])) for r in rows if int(r[4][:-1]) >= 50])"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Write a script that reads a CSV of hosts (name, environment, CPU percent, disk percent) and prints which hosts need attention, grouped by environment.

Clarifying questions to ask

Which values need converting? Which collection holds the hosts of each environment? How do you skip hosts listed in a maintenance file? What exit code should the script return?

Rough sizing

Say 400 hosts in three environments, with a maintenance list of 20 hosts.

Shape of the answer

csv.DictReader for rows; int() on the percentages with a try/except for bad rows; a defaultdict(list) keyed by environment; a set of maintenance hosts read from a file; a comprehension for each environment's alerts; sorted output with f-strings; exit 1 if any alert.

Trade-offs to name

Converting early makes every later comparison correct and needs a decision about bad rows (skip, or fail). A set for the maintenance list is fast and loses order, which does not matter here.

Saved on this device, in this browser.
Next in this series · Lesson 35
Python Functions, Modules, and Packaging

A script becomes a tool when its logic lives in functions with clear inputs and outputs, those functions live in modules other code can import, and the whole thing installs into a virtual environment with pinned dependencies and…

Go to Lesson 35 →

Or browse the full course from the Lessons index.