Pcornel
Browse topics
Options
Recent
Favorites
Networking · Technical reference

Python Conditionals & Functions

Direct 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.

When to use this

Use it when writing validation or data-transformation logic, or when a script skips items or runs forever.

First 30 seconds

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.

Operational verification

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

Failure signatureAutomation works in tests but fails on the first unusual device

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
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 writing validation or data-transformation logic, or when a script skips items or runs forever.
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.

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

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 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

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.

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

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, elif and else take the place of switch statements.
  • match statements: compare a value against patterns, and only the first matching case runs.
  • Loops: for iterates over the items of a sequence, and range() never includes its end value. break and continue control loops, and a loop's else branch runs only if the loop wasn't left with break.
  • Functions: defined with def, they return None if nothing else is returned. Default arguments are evaluated once, so mutable defaults like [] are shared between calls.

Patterns in network scripts

NeedConstruct
Different handling per platformmatch platform: with case "ios-xe":
Skip devices that are unreachablecontinue in the loop
Stop at the first failurebreak, with the loop's else reporting success
Reuse a check on every deviceA function with clear parameters and a return value
Optional settingsKeyword 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

PointWhy it matters
A default like ignore=[] is shared between callsUse None and create the list inside
Don't change a list while looping over itLoop over a copy, or build a new list
Keyword arguments come after positional onescheck_ports(lines, 110, ignore=["Gi1/0/48"])
A function without return gives NoneCallers 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.

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

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.

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 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%
Depth when you need it

Deep reference

Design & tradeoffs

ENCOR design tradeoffs

Small pure functions make automation easier to test before connecting it to network writes.

Confirmation

Confirm action

Continue?