Pcornel
Networking · Automation and Artificial Intelligence

Python Conditionals & Functions

Cheat sheet · https://pcornel.dk/topic.php?topic=92

Back to the Topic

Answer

Conditionals (if/elif/else), loops (for, while) and functions (def) let a script decide, repeat and reuse logic — for example checking each interface's state and reporting the ones that are down.

Remember

Test edge cases: empty lists, None and unexpected values. A function should do one thing and return a value rather than print. Wrap network calls in try/except to handle timeouts without stopping the whole run.

First checks

  • python3 --version and which python3 — interpreter in use.
  • python3 -m venv .venv && . .venv/bin/activate — isolated environment.
  • pip list — installed libraries (requests, netmiko, ncclient, pyyaml).
  • python3 -m py_compile script.py — syntax check.
  • python3 -i script.py / print(type(x), x) — inspect values while debugging.

Verify in this order

correct interpreter and libraries → script parses → inputs read and validated → logic runs → output or change verified

Where it usually breaks

physical/link dependency → local object state → peer/control state → policy → forwarding/adjacency → end-to-end result

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=92

Confirmation

Confirm action

Continue?