Automation and Artificial Intelligence · Topic 1 of 7

Reading Basic Python Scripts

Interpret basic Python in network automation: variables, lists, dictionaries, loops, conditions, functions, errors, JSON handling and a short REST script.

  • 5 min
In a nutshell
  • A list uses square brackets and is read by position, starting at 0.
  • A dictionary uses braces and is read by key.
  • Python uses indentation, and a colon, to mark blocks.

What it is

Python is the main language for network automation, and the exam asks you to read short scripts and say what they do.

You are not asked to write long programs. You need to recognise the building blocks, follow the flow of a script and predict its output. The same few parts appear again and again.

ScriptPython fileimportsLibrariesrequests, jsoncallsDevice or APIreturns dataparsed intoPython objectsdict and list

How it works

A script is a sequence of statements, and the indentation shows the structure.

Variables and data types

A variable holds a value. Python works out the type from the value.

TypeExampleNotes
str"R1"Text, in single or double quotes
int65001Whole number
float0.5Number with a decimal point
boolTrueTrue or False, with a capital letter
list["R1", "R2"]Ordered, changeable, indexed from 0
dict{"name": "R1", "asn": 65001}Key and value pairs
tuple("R1", 22)Ordered, cannot be changed

A list is read by position, and a dictionary is read by key.

devices = ["R1", "R2", "R3"]
router = {"name": "R1", "asn": 65001}
print(devices[0])        # R1
print(router["asn"])     # 65001

Conditions and loops

An if statement chooses a path. A for loop repeats a block for each item. The block is marked by a colon and by indentation, and the indentation is part of the syntax.

for name in devices:
    if name == "R2":
        print(name, "is the border router")
    else:
        print(name, "is internal")

This prints one line for each device. Note that == compares two values, and a single = assigns.

A while loop repeats while a condition is true. The range() function makes a sequence of numbers, so range(3) gives 0, 1 and 2.

Functions

A function is a named block that you can call. The def keyword defines it, and return sends a value back.

def is_up(status):
    return status == "up"

print(is_up("up"))      # True
print(is_up("down"))    # False

Strings and f-strings

An f-string puts values inside text, using braces.

host = "R1"
print(f"Connecting to {host}")   # Connecting to R1

Errors

A try block runs code that might fail. An except block handles the error.

try:
    value = int("abc")
except ValueError:
    print("Not a number")

Without the try, the script would stop with a traceback. Reading a traceback from the bottom up tells you the error type and the line.

Imports and libraries

The import statement brings in a library. The standard json library converts between text and Python objects. The requests library, which is installed separately, makes HTTP calls.

import json

text = '{"hostname": "R1", "interfaces": ["Gi1", "Gi2"]}'
data = json.loads(text)
print(data["hostname"])           # R1
print(len(data["interfaces"]))    # 2

The function json.loads turns a JSON string into a dictionary. The function json.dumps does the reverse. A JSON object becomes a dict, and a JSON array becomes a list.

Reading a REST call

This script reads a list of interfaces from a RESTCONF endpoint.

import requests
from urllib.parse import urlunsplit

HOST = "10.1.1.1"
path = "/restconf/data/ietf-interfaces:interfaces"
url = urlunsplit(("https", HOST, path, "", ""))
headers = {"Accept": "application/yang-data+json"}

response = requests.get(url, headers=headers, auth=("admin", "PASSWORD"), verify=False)

if response.status_code == 200:
    for item in response.json()["ietf-interfaces:interfaces"]["interface"]:
        print(item["name"])
else:
    print("Error", response.status_code)

Read it in steps. The script builds a URL, sets a header, and sends a GET request with a user name and password.

If the status code is 200, it turns the body into a dictionary and prints the name of each interface. Otherwise it prints the code.

The argument verify=False turns off certificate checks, which is acceptable only in a lab. A real script should keep them on.

Build URLhost and pathGET with headersResponsestatus code and bodyif 200Parse JSONdict and listloopPrint namesone per interface

Working with files

The with open pattern opens a file and closes it again automatically.

with open("devices.txt") as f:
    for line in f:
        print(line.strip())

Running a script

The line if __name__ == "__main__": marks code that runs only when the file is started directly, and not when another script imports it. Many scripts put their main logic under it.

What to remember for the exam

Eight facts cover most questions on this topic.

  • A list uses square brackets and is read by position, starting at 0.
  • A dictionary uses braces and is read by key.
  • Python uses indentation, and a colon, to mark blocks.
  • == compares values, and = assigns a value.
  • def defines a function and return gives back a value.
  • json.loads converts a JSON string to Python, and json.dumps converts Python to JSON.
  • A try and except pair handles errors without stopping the script.
  • A JSON object becomes a dict, and a JSON array becomes a list.
Exam tip

When you read a script, start with the imports, then find what the loop or condition does with the data. Predict the output line by line.

Common mistakes

These four mistakes appear often.

Using = where == is needed. A single equals sign assigns, so it cannot compare.

Counting list positions from 1. The first item is at position 0.

Mixing up a dict key with a list index. A dictionary needs a key in quotes, and a list needs a number.

Ignoring indentation. Lines that are indented differently belong to different blocks.

Watch out

Do not leave verify=False in a script that talks to production devices, since it removes the check on the server certificate.

Check yourself

Work through these three questions.

  • What does router["asn"] return when router is a dictionary?

    It returns the value stored under the key asn.

  • What is the position of the first item in a Python list?

    Position 0.

  • Which function turns a JSON string into a Python dictionary?

    json.loads.

Topic 1 of 7 in Automation and Artificial Intelligence

Test yourself on Automation and Artificial Intelligence

The full Cisco CCNP 350-401 ENCOR question bank has 854 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by Cisco. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.