Skip to content
Study CCNP

Interpret

6.1 Interpret basic Python components and scripts

4 min read ENCOR 350-401 v1.2

Aligned to Cisco's 350-401 ENCOR v1.2 exam topics.

On this page

ENCOR does not expect you to write a production automation platform from scratch. It expects you to read a short Python script and understand what it does.

That matters in real life. A network engineer often inherits scripts: one pulls inventory from Catalyst Center, another checks interface status, another builds a JSON payload for RESTCONF. If you can read the script, you can troubleshoot it. If you cannot read it, automation becomes a black box.

The Python you must recognize

Python code is usually built from a few common pieces.

Variables

A variable is a name that points to a value.

hostname = "R1"
mgmt_ip = "10.10.10.11"
retries = 3
reachable = True

The exam may ask what a script prints or which value changes. Track the variable assignments from top to bottom.

Strings

A string is text.

interface = "GigabitEthernet1"
status = "up"
print(interface + " is " + status)
print(f"{interface} is {status}")

Both print:

GigabitEthernet1 is up

The f"..." form is an f-string. It inserts variable values inside braces.

Lists

A list is an ordered collection.

devices = ["R1", "R2", "SW1"]
print(devices[0])
print(devices[-1])

Output:

R1
SW1

Python indexes start at 0. That is a common exam trap.

Dictionaries

A dictionary stores key-value pairs. In network automation, dictionaries often represent devices, interfaces, credentials, or API responses.

device = {
    "hostname": "R1",
    "mgmt_ip": "10.10.10.11",
    "platform": "IOS-XE"
}

print(device["hostname"])
print(device.get("mgmt_ip"))

Output:

R1
10.10.10.11

Use square brackets when the key must exist. Use .get() when the key might be missing.

Conditionals

A conditional runs code only when a test is true.

admin_status = "up"
oper_status = "down"

if admin_status == "up" and oper_status == "up":
    print("forwarding")
elif admin_status == "up" and oper_status == "down":
    print("problem")
else:
    print("disabled")

Output:

problem

Watch the difference between = and ==.

  • = assigns a value.
  • == compares values.

Loops

A loop repeats work.

interfaces = ["Gi1", "Gi2", "Gi3"]

for interface in interfaces:
    print(interface)

Output:

Gi1
Gi2
Gi3

A loop over a dictionary usually gives you keys unless you ask for values or key-value pairs.

device = {"hostname": "R1", "mgmt_ip": "10.10.10.11"}

for key, value in device.items():
    print(f"{key}: {value}")

Functions

A function gives a name to reusable logic.

def is_up(interface):
    return interface["admin"] == "up" and interface["oper"] == "up"

port = {"name": "Gi1", "admin": "up", "oper": "down"}
print(is_up(port))

Output:

False

When reading a function, look at three things:

  1. inputs;
  2. processing;
  3. return value.

Exceptions

Exceptions handle failures.

try:
    count = int("not-a-number")
except ValueError:
    print("Could not convert value")

This script does not crash. It prints:

Could not convert value

In network scripts, exceptions often catch unreachable devices, authentication failures, invalid JSON, or API timeouts.

Reading JSON with Python

Python dictionaries look similar to JSON, but they are not the same thing. Python can load real JSON with the json module.

import json

raw = '{"hostname": "R1", "mgmt_ip": "10.10.10.11"}'
device = json.loads(raw)

print(device["hostname"])

Output:

R1

To read a JSON file:

import json

with open("inventory.json") as f:
    inventory = json.load(f)

for device in inventory["devices"]:
    print(f'{device["hostname"]}: {device["mgmt_ip"]}')

Network automation script example

This script reads an inventory and prints only IOS XE devices.

import json

with open("inventory.json") as f:
    inventory = json.load(f)

for device in inventory["devices"]:
    if device["platform"] == "IOS-XE":
        print(f'{device["hostname"]} {device["mgmt_ip"]}')

Given this inventory.json:

{
  "devices": [
    {
      "hostname": "R1",
      "mgmt_ip": "10.10.10.11",
      "platform": "IOS-XE"
    },
    {
      "hostname": "FW1",
      "mgmt_ip": "10.10.10.21",
      "platform": "ASA"
    }
  ]
}

The output is:

R1 10.10.10.11

That is exactly the kind of script you should be able to interpret.

API example with requests

Python often uses the requests library for HTTP APIs.

import os
import requests

base_url = "https://cat-center.example.com"
token = os.environ["CAT_CENTER_TOKEN"]
ca_bundle = os.environ.get("REQUESTS_CA_BUNDLE", True)

headers = {
    "X-Auth-Token": token,
    "Content-Type": "application/json"
}

response = requests.get(
    f"{base_url}/dna/intent/api/v1/network-device",
    headers=headers,
    timeout=10,
    verify=ca_bundle
)

print(response.status_code)
if response.status_code == 200:
    devices = response.json().get("response", [])
    if devices:
        print(devices[0]["hostname"])
    else:
        print("No devices matched the request")
else:
    print(response.text)

Read it in English:

  1. Import the HTTP library.
  2. Define a controller URL and read the token from an environment variable.
  3. Put the token in the request headers.
  4. Send a GET request to the network-device endpoint.
  5. Print the HTTP status code.
  6. Parse the JSON payload only after confirming the response is usable.

The original one-liner style is fine for a throwaway demo, but it teaches a bad habit: assuming the body exists, the status is successful, and the list has at least one element. ENCOR automation questions often test exactly those assumptions.

You do not need to memorize every endpoint. You need to recognize the flow.

For a disposable sandbox with a self-signed certificate you may temporarily see verify=False, but do not treat that as the safe pattern. REST API security in ENCOR v1.2 explicitly includes TLS and certificate validation, authentication, authorization, token handling, and secrets.

Common exam traps

  • Python indexes start at 0.
  • JSON is parsed into Python dictionaries and lists.
  • print() displays a value; return sends a value back from a function.
  • = assigns; == compares.
  • .json() parses an HTTP response body as JSON.
  • A loop variable such as device is just a temporary name for the current item.
  • Indentation matters. In Python, indentation defines code blocks.

Lab: parse interface state

Goal

Read a small JSON file and print interfaces that are administratively up but operationally down.

Files

Create interfaces.json:

{
  "hostname": "SW1",
  "interfaces": [
    {
      "name": "GigabitEthernet1/0/1",
      "admin": "up",
      "oper": "up"
    },
    {
      "name": "GigabitEthernet1/0/2",
      "admin": "up",
      "oper": "down"
    },
    {
      "name": "GigabitEthernet1/0/3",
      "admin": "down",
      "oper": "down"
    }
  ]
}

Create find_problem_ports.py:

import json

with open("interfaces.json") as f:
    data = json.load(f)

print(f"Device: {data['hostname']}")

for interface in data["interfaces"]:
    if interface["admin"] == "up" and interface["oper"] == "down":
        print(f"Check {interface['name']}: admin up, oper down")

Run it:

python3 find_problem_ports.py

Expected output:

Device: SW1
Check GigabitEthernet1/0/2: admin up, oper down

Stretch task

Change the script so it builds a list named problem_ports and prints the total count at the end.

problem_ports = []

for interface in data["interfaces"]:
    if interface["admin"] == "up" and interface["oper"] == "down":
        problem_ports.append(interface["name"])

print(f"Problem ports: {len(problem_ports)}")

What to memorize

  • list: ordered collection, accessed by number;
  • dictionary: key-value collection, accessed by key;
  • loop: repeats work;
  • conditional: makes a decision;
  • function: reusable block of logic;
  • exception: handles an error;
  • json.load(): reads JSON from a file;
  • response.status_code: HTTP result;
  • response.json(): parsed JSON body.

Exam-ready summary

For ENCOR, read Python like a troubleshooting flow. Follow variables, collections, loops, conditionals, and function returns. When a script touches an API, identify the URL, method, headers, response code, and parsed JSON fields. That is enough to handle most automation-code questions in this domain.

Sources used

  • Cisco ENCOR 350-401 v1.2 exam topics: https://learningcontent.cisco.com/documents/marketing/exam-topics/350-401-ENCORE-v1.2.pdf