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



example1.py
example2.py
◇ 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:
    print(f.read())

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


◇ Requesting interactive user input
input( )
◇ Writing to the command line
print( )

example3.py
◇ 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

python -i script.py
# or
python script.py

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


Helpful Interactive Python Commands



# Return all variable, classes, objects (collectively under 'names') available
>>> dir()
## Output
['__builtins__''__doc__''__loader__''__name__''__package__''__spec__']

>>> from datetime import datetime
>>> dir()
## Output
['__builtins__''__doc__''__loader__''__name__''__package__''__spec__''datetime']

>>> import example1
>>> dir()
## Output
['__builtins__''__doc__''__loader__''__name__''__package__''__spec__''datetime''example1']



# Return attributes of an object
# dir(name)
>>> dir(example1)
## Output (partial)
['__author__''__author_email__''__builtins__''__cached__''__copyright__''doubler']

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


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

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







Index