Use it when writing validation or data-transformation logic, or when a script skips items or runs forever.
Python Conditionals & Functions
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.
1. Add print() (or use a debugger) inside the loop — is each item visited?
2. Condition never true → compare types ('1' == 1 is False).
3. Endless while → the loop variable never changes.
4. Function returns None → missing return.
5. Test with an empty input and a failing device.
correct interpreter and libraries → script parses → inputs read and validated → logic runs → output or change verified
A function returns wrong results or raises an exception when a value is empty, unexpected or an error response.
Possible stored cause: Only the expected (happy) path was tested; edge cases and error branches were never exercised.Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
A function returns wrong results or raises an exception when a value is empty, unexpected or an error response.
Step 1 Verification & evidence Verify boundary
Predict function inputs/outputs and test both success/failure branches.
Step 2 Common failure modes Narrow the fault
Only happy path tested, condition order wrong, return value ignored or exception handling hides a real failure.
Step 3 Troubleshooting workflow Narrow the fault
Focus for this topic: Only happy path tested, condition order wrong, return value ignored or exception handling hides a real failure.
Step 4 Common mistakes Narrow the fault
- Using
=instead of==in a condition (SyntaxError in Python). - Mutable default arguments (
def f(x=[])). - Functions that print instead of returning values, so results cannot be reused.
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.
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.
python3 --versionandwhich 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
Branching, loops and reusable functions for validation and data transformation.
Key ideas: Conditionals encode operational rules; functions isolate reusable logic such as validation, normalization and API calls.
ReferenceWhy it matters1 section · depth on demand
Why it matters
Conditionals encode operational rules; functions isolate reusable logic such as validation, normalization and API calls.
ReferenceImportant terms & boundaries2 sections · depth on demand
In depth
Conditionals and functions in automation scripts
Decisions and reusable functions turn a list of commands into a dependable tool. The official Python tutorial covers the building blocks:
- Conditionals:
if,elifandelsetake the place of switch statements. matchstatements: compare a value against patterns, and only the first matching case runs.- Loops:
foriterates over the items of a sequence, andrange()never includes its end value.breakandcontinuecontrol loops, and a loop'selsebranch runs only if the loop wasn't left withbreak. - Functions: defined with
def, they returnNoneif nothing else is returned. Default arguments are evaluated once, so mutable defaults like[]are shared between calls.
Patterns in network scripts
| Need | Construct |
|---|---|
| Different handling per platform | match platform: with case "ios-xe": |
| Skip devices that are unreachable | continue in the loop |
| Stop at the first failure | break, with the loop's else reporting success |
| Reuse a check on every device | A function with clear parameters and a return value |
| Optional settings | Keyword arguments with safe defaults (None, not []) |
def parse_status(line):
'''Return (interface, status, vlan) from one show-interfaces-status line.'''
fields = line.split()
return fields[0], fields[-5], fields[-4]
def check_ports(lines, expected_vlan, ignore=None):
if ignore is None:
ignore = []
problems = []
for line in lines:
intf, status, vlan = parse_status(line)
if intf in ignore:
continue
if status == "err-disabled":
problems.append((intf, "err-disabled"))
elif status == "connected" and vlan != str(expected_vlan):
problems.append((intf, f"vlan {vlan}"))
return problems
def command_for(platform):
match platform:
case "ios" | "ios-xe":
return "show interfaces status"
case "nxos":
return "show interface status"
case _:
raise ValueError(f"unsupported platform {platform}")
Tutorial points that prevent bugs
| Point | Why it matters |
|---|---|
A default like ignore=[] is shared between calls | Use None and create the list inside |
| Don't change a list while looping over it | Loop over a copy, or build a new list |
| Keyword arguments come after positional ones | check_ports(lines, 110, ignore=["Gi1/0/48"]) |
A function without return gives None | Callers must check for it |
Small, testable functions like parse_status can be unit-tested with sample output. That is far easier than testing a whole script against live devices.
Documented example, not captured output.
Quick reference
Conditionals let a script make decisions, and functions package logic so it can be reused and tested. Together they turn one-off scripts into reliable tools: the same function can check an interface during a change, generate a report or run in an automated test.
Conditionals and functions:
def interface_state(intf: dict) -> str:
if intf["admin"] == "down":
return "disabled"
elif intf["oper"] == "up":
return "ok"
return "fault"
for i in [{"name":"Gi1/0/1","admin":"up","oper":"down"}]:
print(i["name"], interface_state(i))
Documented example, not captured output. Keep functions small and testable; return data rather than printing, so the same function can feed reports, checks and tests.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Automation and Artificial Intelligence → Python Conditionals & Functions. 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%Deep reference
Design & tradeoffs
ENCOR design tradeoffs
Small pure functions make automation easier to test before connecting it to network writes.