Interpret Basic Python Components and Scripts

In this blog post, we will provide an introduction to Python components and scripts in the context of Cisco certification. We will show how to get started with Python and explain the most commonly used elements of Python scripts – variables, functions, program flow, conditional logic, and “for” loops.

Interpret Basic Python Components and Scripts

The content aims to help CCNP/CCIE Enterprise track candidates to prepare for the ENCOR exam, which includes the following topic:

6.1 Interpret basic Python components and scripts

Many CCNP tracks have automation sections that assume some knowledge of Python. DevNet track expects more extensive knowledge in Python.

Python Installation

Python is an interpreted language, which means that the code of a program is not pre-compiled into an executable that contains machine instructions. Python code can be opened and edited with any text editor. Python programs have a .py extension.

To run a Python code an interpreter is required. It reads the code and converts it into machine instructions.

Python is available for different platforms. Python 3.x is the recommended version and we will use it in our examples.

To download Python installation files navigate to this URL. Start the installer.

We use Windows 10 in our examples. Enable the checkbox “Add Python 3.x to PATH” and press Install Now.

Figure 1. Python Installation Options
Figure 1. Python Installation Options

Start Windows CLI utility by starting typing “Command Prompt”. Once started type in the following command to confirm that Python interpreter is available.

Microsoft Windows [Version 10.0.18362.836]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\PythonExamples>python --version
Python 3.8.3

Keep the command prompt window opened.

Hello World!

We will start with a simple “Hello World!” example.

Open a text editor, such as Notepad, and type-in the following code:

print("Hello World!")

The example uses a built-in print() function that displays a message on the screen.

Save the file as hello_world.py in a folder on your computer. To run the program, we will pass the full file name to python interpreter:

C:\PythonExamples>python c:\PythonExamples\hello_world.py
Hello World!

Variables

A variable stores some value, which can be accessed in the code by using its name. In Python, variables are not declared and can be used by assigning a value to them.

Let’s add a few more lines to the hello_world file. The new code creates a line number variable that is changed after each use. First two times it was statically set to 2 and 3, and in the line, before the last, we’ve just incremented its value by 1. The print function is being provided with 2 arguments – descriptive text and the line number variable.

print("Hello World!")
line_number = 2
print("This is the line number", line_number)
line_number = 3
print("This is the line number", line_number)
line_number = line_number + 1
print("This is the line number", line_number)

When the program is launched the following output is displayed on the screen.

C:\PythonExamples>python c:\PythonExamples\hello_world.py
Hello World!
This is the line number 2
This is the line number 3
This is the line number 4

Functions

A function minimizes the amount of duplicate code. It can also provide better structure and improve the readability of program code, by wrapping related logic under the function definition, which can be called by a descriptive name from other places of the program.

Let’s adjust our program to demonstrate the use of functions.

def line_number_printer(number):
    print("This is the line number", number)

def calculate_next_line_number(previous_number):
    return previous_number + 1

print("Hello World!")
line_number = 2
line_number_printer(line_number)
line_number = calculate_next_line_number(line_number)
line_number_printer(line_number)
line_number = calculate_next_line_number(line_number)
line_number_printer(line_number)

The program produces exactly the same output as the code in the previous example.

We have introduced 2 functions:

  • line_number_printer(number)
  • calculate_next_line_number(previous_number)

Figure 2 shows how the functions are defined and used in the example above. Not all lines from the example are shown for brevity.

Figure 2. Python Functions Example
Figure 2. Python Functions Example

Let’s go through the diagram and discuss each element:

  1. A function’s definition must precede its use. The code within the definition is not executed unless it is called.
  2. Function definition starts with a keyword “def”.
  3. The function name should be in lower case with underscore used as a word separator. Python’s style guide is called PEP 8. It explains different elements of style, such as the naming convention and how the code must be formatted (https://www.python.org/dev/peps/pep-0008).
  4. A function can accept a value as an input in the form of parameter. Variable name in parentheses stores value supplied when the function was called. This variable is available for use within the function body.
  5. The line containing function definition ends with a colon showing that function statements will follow in the next lines.
  6. The code statements within a function are indented. PEP 8 recommends the use of spaces for indentation instead of tabs. Also, 4 spaces should separate each indentation level.
  7. A function can be invoked to perform some action without returning any values to the caller. It can also return a value; such as a result of a calculation or a success code back to the caller. To create such a function, a statement starting with keyword return is used. When this statement is encountered, function execution stops.

Conditional Logic

Conditional logic statements allow us to perform certain actions based on an evaluation result of a condition. Let’s modify our example, so the line_number_print function displays different strings depending on whether the number is odd or even. The listing below shows the modifications made, the remaining code is not changed.

def line_number_printer(number):
    if number % 2 == 0:
        print("This is the line number", number, "and it is even")
    else:
        print("This is the line number", number, "and it is odd")

When the program is launched the following output is displayed on the screen.

C:\PythonExamples\>python c:\PythonExamples\hello_world.py
Hello World!
This is the line number 2 and it is even
This is the line number 3 and it is odd
This is the line number 4 and it is even

Figure 3 shows how conditional logic is used in the example above.

Figure 3. Python Conditional Logic Example
Figure 3. Python Conditional Logic Example

Let’s go through the diagram and discuss each element:

  1. “if” keyword is followed by a logical test that can be either True or False.
  2. If the test is evaluated as True, the statement (or multiple statements) under the “if” section is executed.
  3. As with the functions, the body of “if” or “else” sections comprises of indented statements.
  4. If the test is evaluated as False, the statement (or multiple statements) under the “else” section is executed.

for Loops

The “for” loops can be used to apply an action to each element of a collection. For example, we can store a list of switch interfaces in a list. To check the status of each of these interfaces we can use the “for” loop to iterate through the list and then run a command against each of the interfaces.

Let’s rewrite our program using “for” loops to automatically assign line numbers.

The listing below shows the complete code, as we removed the line calculation function and multiple calls to print function.

def line_number_printer(number):
    if number % 2 == 0:
        print("This is the line number", number, "and it is even")
    else:
        print("This is the line number", number, "and it is odd")

print("Hello World!")
for line_number in range(2, 5):
    line_number_printer(line_number)

When the program is launched the same output is displayed on the screen.

C:\PythonExamples>python c:\PythonExamples\hello_world.py
Hello World!
This is the line number 2 and it is even
This is the line number 3 and it is odd
This is the line number 4 and it is even

Figure 4 shows how “for” loop is used in the example above.

Figure 4. Python "for" loop Example
Figure 4. Python “for” loop Example

Let’s go through the diagram and discuss each element:

  1. “for” keyword is followed by a variable name that will be changing its value on each pass.
  2. “in” keyword is followed by a list of values that will be assigned one at a time to the “for” variable on each iteration.
  3. Statements that perform actual work during each cycle are indented under the “for” loop.

Not shown in the example, “break” keyword stops loop processing and continues with the code following the loop. Similarly, the “continue” keyword stops the current pass processing, but in contrast to “break”, it starts the next cycle of the loop.

Self-Test Tasks:

Task 1

Write a function that accepts a number and prints it out followed by “is the number passed as a parameter”.

Task 2

Write a function that accepts a number and prints out “Greater than 10” or “Less or equal than 10” depending on the number that was provided. The greater operator is “>” and less or equal is “<=”.

Task 3

Write a “for” loop that iterates over a list of interfaces Ethernet1/1, Ethernet1/2, and Ethernet1/3 and prints out the output below. To supply interfaces for “for” loop, use a list [ “Ethernet1/1”, “Ethernet1/2”, “Ethernet1/3” ]

interface Ethernet1/1
 description Added by Automation Script
 no shutdown
interface Ethernet1/2
 description Added by Automation Script
 no shutdown
interface Ethernet1/3
 description Added by Automation Script
 no shutdown

Self-Test Answers:

Task 1

def print_number(number):
    print(number, "is the number passed as a parameter")

Task 2

def compare_number_to_ten(number):
    if number > 10:
        print("Greater than 10")
    else:
        print("Less or equal than 10")

Task 3

for interface_name in [ "Ethernet1/1", "Ethernet1/2", "Ethernet1/3" ]:
    print("interface", interface_name)
    print(" description Added by Automation Script")
    print(" no shutdown")