Pcornel
Browse topics
Options
Recent
Favorites
Networking · Technical reference

Python Fundamentals

Direct answer

Python fundamentals for network automation: variables, types (str, int, float, bool, None), expressions, f-strings, imports and reading a script top to bottom.

When to use this

Use it when reading or writing a small automation script, or when a script fails with a type or syntax error.

First 30 seconds

1. python3 --version — the expected interpreter (3.9+)?

2. Read the traceback's last line: SyntaxError, NameError, TypeError, KeyError?

3. TypeError → print type(x); convert strings with int() / str().

4. ModuleNotFoundError → activate the venv, pip install <lib>.

5. Re-run with a small known input.

Operational verification

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

Failure signaturePython automation script fails before it touches a device

The script stops with IndentationError, TypeError or KeyError on the first run.

Possible stored cause: Indentation is mixed, or values have a different type than expected (string vs int, None from a missing field).
Context & applicabilityCommon mistakes · platform/version boundaries
Common mistakes
Common mistakes

Local intent: Variables, types, expressions and basic script reading for network automation.

Platform / version applicability
Cisco IOS / IOS XE
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformCisco IOS / IOS XE
Scope / prerequisiteUse it when reading or writing a small automation script, or when a script fails with a type or syntax error.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

The script stops with IndentationError, TypeError or KeyError on the first run.

Step 1 Verification & evidence Verify boundary

Read small scripts, predict variable values/output, and test data transformations in safe tooling.

Step 2 Common failure modes Narrow the fault

Type/indentation errors, assumptions about strings vs integers, unhandled missing keys or destructive automation without validation.

Step 3 Troubleshooting workflow Narrow the fault

Focus for this topic: Type/indentation errors, assumptions about strings vs integers, unhandled missing keys or destructive automation without validation.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Command lookup Jump straight to Cisco syntax
Key points

Indentation is syntax. Strings from APIs or CLI output are text — convert with int() before arithmetic. Use a virtual environment per project and pin library versions. Read the traceback from the bottom: the last line is the error, the line above it is where.

Key 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.
ReferenceWhat it is1 section · depth on demand

Concept overview

Variables, types, expressions and basic script reading for network automation.

Key ideas: Python lets network engineers transform data, call APIs and generate deterministic configuration/workflows. ENCOR-level skill emphasizes understanding common constructs and script behavior.

ReferenceWhy it matters1 section · depth on demand

Why it matters

Python lets network engineers transform data, call APIs and generate deterministic configuration/workflows. ENCOR-level skill emphasizes understanding common constructs and script behavior.

ReferenceHow it works1 section · depth on demand

Mechanism, scope & boundaries

Local intent: Variables, types, expressions and basic script reading for network automation.

ReferenceImportant terms & boundaries3 sections · depth on demand

Important terms and limits

Path: Networking → Automation and Artificial Intelligence → Python Fundamentals. Local intent: Variables, types, expressions and basic script reading for network automation.

In depth

Python basics for network engineers

Python is the most common language for network automation, and a few fundamentals cover most daily scripts. The official Python tutorial introduces them:

  • The interactive interpreter, where >>> marks input.
  • Assignment with =, including multiple assignment such as a, b = 0, 1.
  • Numbers. / always returns a float, // floor-divides and % gives the remainder.
  • Strings. Single and double quotes are equivalent, raw strings (r'...') keep backslashes, strings are immutable, and indexing and slicing start at 0.
  • Lists, which are mutable. Simple assignment never copies a list.

Fundamentals with network examples

ConceptExample
Variableshostname = "acc-2f-01"
Integers and arithmeticvlan = 110, hosts = 2 ** (32 - 26) - 2 gives 62
Floor division and moduloslot, port = divmod(49, 48)
Strings and slicing"GigabitEthernet1/0/14"[:2] gives "Gi"
String methodsline.strip().split()
Listsvlans = [110, 120, 999]; vlans.append(130)

Common pitfalls (tutorial)

PitfallExplanation
8 / 4 gives 2.0/ always returns a float; use // for integers
Changing a string in placeStrings are immutable; build a new one
b = a with listsBoth names refer to the same list; copy with a[:]
-3**2 is -9** binds more tightly than unary minus
dev$ python3
>>> hostname = "acc-2f-01"
>>> mgmt_ip = "10.255.1.21"
>>> f"{hostname} ({mgmt_ip})"
'acc-2f-01 (10.255.1.21)'
>>> intf = "GigabitEthernet1/0/14"
>>> intf[:2] + intf[-6:]
'Gi1/0/14'
>>> prefix = 26
>>> 2 ** (32 - prefix) - 2
62
>>> output = "Gi1/0/14  connected  110  a-full  a-1000"
>>> output.split()[2]
'110'
>>> import ipaddress
>>> ipaddress.ip_interface("10.110.0.64/24").network
IPv4Network('10.110.0.0/24')

Next steps

Data structures (lists and dictionaries for inventories), conditionals and functions (decisions and reusable code), and libraries for data formats and APIs build on these basics. Prefer the standard ipaddress module over hand-written subnet arithmetic.

Documented example, not captured output.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Quick reference

Python is the most widely used language for network automation because it is readable, has a large ecosystem of networking libraries and runs on every platform. A few basic constructs — variables, lists, loops and formatted strings — are enough to generate configurations and collect data from devices. The libraries listed here handle the connections, so scripts can focus on the logic.

Python basics for network automation:

hostname = "sw1"
vlans = [10, 20, 30]
for vlan in vlans:
    print(f"vlan {vlan}\n name VLAN{vlan}")

Useful libraries: Netmiko (SSH CLI), NAPALM (multi-vendor getters/config), ncclient (NETCONF), requests/httpx (REST), Nornir (inventory and parallel tasks), pyATS/Genie (parsing and testing), TextFSM/TTP (parse CLI output). Use virtual environments (python3 -m venv .venv) and never hard-code credentials — read them from environment variables or a vault.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docCisco IOS / IOS XE Current documentation reviewed 2026-09-14

Authoritative/upstream documentation reviewed for bounded claims in Automation and Artificial Intelligence → Python Fundamentals. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://www.cisco.com/c/en/us/support/ios-nx-os-software/ios-xe-17/series.html · confidence 94%
Depth when you need it

Deep reference

Design & tradeoffs

ENCOR design tradeoffs

Automation should start with small, testable transformations before making network changes.

Confirmation

Confirm action

Continue?