Python Language and Script Basics

Why Python and How to get it?

• Python is powerful... and fast;
• plays well with others;
• run everywhere;
◇ on a computer (Windows, macOS, or Linux), on a server, in a VM, in a container, in the cloud, and on some Cisco IOS devices
• is friendly & easy to learn;
• is Open
• The Zen of Python by Tim Peters


Why Python for Network Engineers?

• Readable and easy to learn
• Widely available and Open Source
◇ Windows, Mac, Linux
◇ Routers & Switches
• Many relevant code samples
• Lots of training resources


Breaking Down Python code
◇ Reading from and writing to files
◇ The “with” statement
▪ context handler
▪ handles cleanups after you're done working with an object

# Using 'with' block
with open(log, "r"as f:

# Without 'with' statement, you've to write like below
f = open(log, "r")

◇ Requesting interactive user input
input( )
◇ Writing to the command line
print( )
◇ Creating and using dictionaries { }
◇ Creating and using lists [ ]
◇ Working with for loops
◇ Conditional statements


Interacting with Python Live

What is and Why Use Interactive Python

• Real-time enter code and see results
• Experimental and learning
• Debug scripts that aren't working
• BUild on the output of a script

Accessing Interactive Python

# Accessing Interactive Python
python -i
# or

python -i
# or

# IDLE is a IDE for python
python -m idlelib.idle      # virtual environment

Helpful Interactive Python Commands

# Return all variable, classes, objects (collectively under 'names') available
>>> dir()
## Output

>>> from datetime import datetime
>>> dir()
## Output

>>> import example1
>>> dir()
## Output

# Return attributes of an object
# dir(name)
>>> dir(example1)
## Output (partial)

>>> print(example1.__author__)
## Output
Hank Preston

# Build-in help system. Display docs and info for object
# help(name)
>>> help(example1.doubler)
## Output
Given a number, double it and return the value

>>> mynum = example1.doubler(32)
>>> print(mynum)
## Output