III-Networking
introduces
Python Basics for Network
Engineers
By: Sajjad Ghaffoori
iiinetworking.com
Our Website
YouTube.com/@iiinetworking
Arabic IT Courses/Content
Page: Facebook.com/iiinetworking
Group: Facebook.com/groups/iiinetworking
Technical Discussion and Sharing
@III_Networking
Entertaining IT Content
Linkedin.com/in/ sajjad-ghaffoori-6b4674134
Linkedin.com/company/iii-networking
Direct Connection
https://t.me/+yDIoeSbd-3EwYzA0
Courses Channel
- Python Programming Language
- A scripted language
- source-free
- object-oriented
- simple understandable text
- standard-library
- indentation sensitive
- tabs or spaces (4)
- can integrate with other encoding languages
- use python interpreter for a quick interface to python processing
- use python editor to code programs to run by python
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Virtual Environments
- A separate directory structure
- with a different python version
- and packages and modules
- independent from the base version
- if a developed application is familiar with/based on
- a specific version of python
- and if upgrading python in the future might
- add a risk to break the functions/code of the application
- using virtual environments will lock components and modules
- of an application, into a single package
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Comments
- insert a note to yourself or other programmers
- to highlight a comment about the code
- comments can start with a hash symbol #
- this will only allow one line for a comment
- no new line for the same comment
- or use the triple quotes ‘’’ ‘’’ enclosing a string
- this allows for multiple lines per comment
- a carriage return won’t break the comment sequence
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Variables
- A label, maps to a stored object
- ask python to process/print the variable label only
- python will take care of the value of that variable
- variable name rules
- must start with an alphabetic letter, or underscore
- but not a number
- case sensitive
- in total, it can contain, letter, numbers, and underscore only
*the object assigned to a variable can be a variety of data types
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- Integers & Floating Points
- An integer is a whole number without a decimal points (10)
- a floating points is a number with a decimal points or exponents
- 10e5 = 100,000 , or 10.5
- Python’s Numeric Operations
+
sum
10+6 = 16
-
subtract
10-6 = 4
*
multiply
10*6 = 60
/
divide
10/6 = 1.6666666666666667
//
divide/no remainder
10//6 = 1
%
modulus division
10%6 = 4
**
exponent
10*6 = 1,000,000
*order of the process is: parentheses --- power --- multiply. --- division --- addition --- subtraction --- L->R
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- Booleans
- A Boolean object can have a value of 2 only
- True or False
- comparison operators evaluates between 2 Boolean objects
- Boolean comparison operators can be
<
less than
6 < 10
TRUE
>
greater than
6 < 10
FALSE
<=
less than or equal
6 <= -10 FALSE
>=
greater than or equal
6 >= -10 TRUE
==
equal to
6 == 10
FALSE
!=
not equal to
6 != 10
TRUE
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- Strings
- a set of characters, stored from left to right
- enclosed by a double quote (“”)
- the string “10” is only a string of 2 characters
- and not considered as an integer to be numerically processed
- using the integer function int()
- a string can be dealt with as an integer
>>> int(’10’) + 6 = 16
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- String index
- the location of a character, counted starting from the left side and from the value of “0”
- the 0 index of the string “Hello” is the “H” character
>>> v = “Hello”
>>> v [0] = “H”
>>> v [0:2] = “He”
>>> v [0:5] = “Hello”
>>> v [:2] = “He”
>>> v [2:] = “llo”
>>> v [-2:] = “lo”
>>> v [:-2] = “Hel”
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- String operations
- operations with string can deal with the characters in a simple manner without modifying them
- “Hello” + “III” = “Hello III”
- “Hello” * 3 =“Hello Hello Hello”
- String Methods
str.capitalize()
Capitalize the string
str.center(width[, fillchar])
Center justify the string
str.endwith(suffix[, start[, end]])
Add an ending string to the string
str.find(sub[, start[, end]])
Find the index position of the characters in a string
str.lstrip([chars])
Remove whitespace characters from the end of the string
str.replace(old, new[, count])
Replace characters in the string
str.lower()
Make the string all lowercase
str.rstrip([chars])
Strip whitespace characters from the front of the string
str.strip([chars])
Remove whitespace characters from the beginning and end of the string
str.upper()
Make the string all uppercase
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- Lists
- A collection of values stored in one variable
- collage the values inside a square bracket []
- separate the values using a comma ,
- Certs = [ “CCNA” , “CCNP” , “CCIE” ]
- values in a list can be a variety of python data types
*lists can be empty, *python supports a built-in list() function
- Lists Index
- each value inside the square brackets has an index, starting from “0”
- Certs[2] = “CCIE”
- List Cat with + operator
- Certs1 = [ “CCNA” , “CCNP” , “CCIE” ] , Certs2 = [ “JNCIA” , “JNCIP” , “JNCIE” ]
- Certs3 = Certs1 + Certs2 == [ “CCNA” , “CCNP” , “CCIE” , “JNCIA” , “JNCIP” , “JNCIE” ]
*same string operations applies to lists operations
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- Tuples
- an immutable lists
- where lists are mutable (modifiable) used for non-constant values
- tuples are immutable (non-modifiable) used for constant values
- Certs = ( 2024 , “ENCOR” , “ENAUTO” )
- support the type() function to declare the tuple class
- same operations of lists apply
- modifying operations won’t work
- try Certs[1] =“NOT-UPDATED” in both lists and tuples
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- Dictionaries
- also, a collection of values
- the collection has no index method
- built using key:value pairs
- keys are immutable: integers, strings, floats, Booleans)
- values are all the python data types including lists and tuples
- Dictionaries themselves are mutable
- they enclose the collection of data using curly braces { }
- and separate each key:value pair using a comma ,
- CompanyInfo = { “Name”:”III” , “Type”:”LLC” , “Age”:2 , “Certs”(“Cisco” , “Juniper” , “AWS”) }
- type(CompanyInfo) == <class ‘dict’>
- to investigate the values, refer to keys instead of index
- CompanyInfo[“Type”] == “LLC”
- adding a new pair can be done just by typing the new values >>> CompanyInfo[“Domain”] = “IT”
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Data Types
- Sets
- as dictionaries, sets uses curly braces, and it is mutable
- a set is just an unordered grouping of data
- frozen sets are immutable sets
>>> values1 = {1, 2, 4, 6, 8, 10, 12}
>>> values2 = {1, 3, 5, 7, 9}
>>> type(values)
<class ‘set’>
- join 2 sets with no duplicates
>>> values1 | values
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
- intersect 2 sets showing only the duplicates
>>> values1 & values2
{1}
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Input & Output Function
- The input() function
- python will prompt a message asking for an input
- from the client or the user of the program
- any input (response) from the user, is considered a string (only)
>>> Username = input (“Type Username: “)
Type Username: III-Networking
>>> Username
“III-Networking”
- in cases where the input is designed to not be a string (default)
- an additional converting function would be needed
>>> Temperature = integer (input (“What is the Temp Today?: “))
What is the Temp Today?: 25
>>> Temperature
25
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Input & Output Function
- The output function
- Named as the Print() Function
- prints the output of a code or a program
>>> print(“Hello III”)
Hello III
- each line processed in the print() function end with a \n character
- which represents the function of “new line”
>>> print(“Hello\nIII”)
Hello
III
- text control codes
\\: Backslash
\b: Backspace
\t: Tab
\r: Carriage Return
\’: Single Quote
\”: Double Quote
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Input & Output Function
- The open() function
- opens and reads a file content, line by line
- the open() function should contain the file name inside the paratheses ()
- and the entire object can be stored in a variable
- an open mode can be specified as well, to determine what should the function do
- to the content in the file
- open() functions should be closed with a close() function
readdata = open(“textfile.txt”, “r”)
print(readdata.read())
readdata.close()
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Input & Output Function
- The open() function
- The with statement
- uses the open() function, without requiring a close() function
with open("textfile.txt", "r") as data:
print(data.read())
- The append “a+” statement
- to append, write data to a file
with open("textfile.txt", "a+") as data:
data.write('\nFourth line added by Python’)
with open ("textfile.txt", "r") as data:
print(data.read())
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Input & Output Function
- The open() function
- modes can be
r: Open for reading (default)
w: Open for writing, truncating the file first
x: Open for exclusive creation, failing if the file already exists
a: Open for writing, appending to the end of the file if it exists
b: Open in binary mode
t: Open in text mode (default)
+: Open for updating (reading and writing)
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Conditionals
- If statements
- evaluates elements and determines its truth
- if statements is a Boolean logic
- a program can start with an “if” statement
- have many “elif” else-if statements
- and closed with an “else” statement
- all of the 3 above conditions are optional, per-program
>>> n = 20
>>> if n == 20:
...
print('The number is 20’)
...
The number is 20
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Conditionals
- Else-if statement
- Else statement
>>> n = 3
score = int(input('What was your test score?:’))
>>> if n == 17:
if score >= 90:
...
print('Number is 17’)
... elif n < 10:
...
print('Number is less than 10’)
... elif n > 10:
...
print('Number is greater than 10’)
...
Number is less than 10
print('Grade is A’)
elif score >= 80:
print('Grade is B’)
elif score >= 70:
print('Grade is C’)
elif score >= 60:
print('Grade is D’)
else:
print('Grade is F’)
What was your test score?:53
Grade is F
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Looping
- repetitive operation per condition
- For Loops
- repeats or continue to iterate based on a specific number of times
>>> numbers=(1,2,3,4,5)
>>> for variable in numbers:
...
print(variable)
...
1
2
3
4
5
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Looping
- For Loops
- the range() function can cooperate with the for loop
- to further customize the looping range or period
- from which value to start and to which value to stop
- as well as the increment value
>>> for x in range(3):
>>> for x in range(1,3):
>>> for x in range(1,11,3):
...
...
...
print(x)
print(x)
...
...
...
0
1
1
1
2
4
2
print(x)
7
10
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Looping
- While Loop
- evaluates and iterates as long as the condition is “TRUE”
- can continue to iterate forever
- can cooperate with the “else” statement
>>> count = 1
>>> while (count < 5):
...
print("Loop count is:", count)
...
count = count + 1
... else:
...
print("loop is finished")
...
Loop count is: 1
Loop count is: 2
Loop count is: 3
Loop count is: 4
loop is finished
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Looping
- While Loop
- to exit the infinite while loop
- a break statement can be involved in the program
while True:
string = input('Enter some text to print. \nType "done" to quit> ‘)
if string == 'done’ :
break
print(string)
print('Done!’)
Enter some text to print.
Type "done" to quit> Good luck on the test!
Good luck on the test!
Enter some text to print
Type "done" to quit> done
Done!
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Functions
- A function in python can take inputs, process, and return outputs
- represents the key concept of DRY
- Don’t Repeat Yourself
- meaning, define a function at the beginning
- refer to it multiple times, in different ways, throughout the code
- Functions Types
- built-in python: the print() function
- custom created functions
- Functions format
- def functionname():
- can’t start with a number
>>> def devnet():
'''prints simple function'‘’
print('Simple function')
>>> devnet()
Simple function
*try help(devnet)
- can’t reuse a default standard function name
- accepts combinations of letters, numbers, and special characters
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Functions
- Positional Arguments
- arguments allows to store multiple values in a function
- the function will later summon a value or more per the code request
- making the function usable for multi-purpose, multi-output
- try the max() function and see the output
>>> max(40, 30, 20, 10)
40
- Parameters
- allows to pass data to a function
- parameters are variables
>>> def sub(arg1, arg2):
result = arg1 - arg2
return result
>>> sub(30, 15)
15
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Functions
- Keyword Arguments
- pass key:value pairs to a function
- positional argument (*args) vs. keyword arguments (**kwargs)
(**args)
(*args)
>>> def hello(*args):
for arg in args:
print("Hello", arg, "!")
>>> hello(‘Mohammed’ , ‘Ali’)
Hello Mohammed !
Hello Ali !
>>> def hello(**kwargs):
for key, value in kwargs.items():
print("Hello", value, "!")
>>> hello(kwarg1=‘Mohammed', kwarg2=‘Ali')
Hello Mohammed !
Hello Ali !
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Classes
- A Class structures data to describe information about an object
- data can be a variety of information for one object
- the first default data should be “self”
class Router:
'''Router Class'‘’
def __init__(self, model, swversion, ip_add):
'''initialize values'‘’
self.model = model
self.swversion = swversion
self.ip_add = ip_add
rtr1 = Router(‘C8Kv', ‘17.2.1', ‘100.64.10.1’)
- test the above program by asking for a specific information
>>> rtr1.model
“C8Kv”
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Classes
- new information/data can be inserted to an object at any time
>>> rtr1.desc = 'virtual router’
>>> rtr1.desc
'virtual router’
- adding a new object (variable) to program doesn’t require to built a new class (DRY)
>>> rtr2= Router('isr4221', '16.9.5', '10.10.10.5‘)
>>> rtr2.model
'isr4221‘
*the __ double Under score is called a method
*try the function getdesc() with methods and classes
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Classes
class Router:
'''Router Class'‘’
def __init__(self, model, swversion, ip_add):
‘''initialize values'‘’
self.model = model
self.swversion = swversion
self.ip_add = ip_add
def getdesc(self):
‘''return a formatted description of the router'‘’
desc = f'Router Model
:{self.model}\n’\
f'Software Version
:{self.swversion}\n’\
f'Router Management Address
:{self.ip_add}’
return desc
rtr1 = Router('iosV', '15.6.7', '10.10.10.1')
rtr2 = Router('isr4221', '16.9.5', '10.10.10.5')
print('Rtr1\n', rtr1.getdesc(), '\n', sep='')
print('Rtr2\n', rtr2.getdesc(), sep='')
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Classes
- classes supports inheritance, to reuse a class for another object
- without redefining the class structure again (DRY)
class Router:
'''Router Class'‘’
def __init__(self, model, swversion, ip_add):
'''initialize values'‘’
self.model = model
self.swversion = swversion
self.ip_add = ip_add
def getdesc(self):
'''return a formatted description of the router'‘’
desc = (f'Router Model
:{self.model}\n’
f'Software Version
:{self.swversion}\n’
f'Router Management Address:
{self.ip_add}’)
return desc
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Classes
class Switch(Router):
def getdesc(self):
'''return a formatted description of the switch'‘’
desc = (f'Switch Model
:{self.model}\n’
f'Software Version
:{self.swversion}\n’
f'Switch Management Address
:{self.ip_add}’)
return desc
rtr1 = Router('iosV', '15.6.7', '10.10.10.1’)
rtr2 = Router('isr4221', '16.9.5', '10.10.10.5’)
sw1 = Switch('Cat9300', '16.9.5', '10.10.10.8’)
print('Rtr1\n', rtr1.getdesc(), '\n', sep=‘’)
print('Rtr2\n', rtr2.getdesc(), '\n', sep=‘’)
print('Sw1\n', sw1.getdesc(), '\n', sep='')
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Modules
- Modular, as English states! ☺
- modules are a groupings of python’s classes and functions
- with a common use for a program
- thousands of libraries are standard python libraries
- many comes in the Python Standard Library upon installation
- others should be manually downloaded using the “pip” command
- thousands more are 3rd party libraries
- reviewing a library
- use the “import” command to summon a library with its functions and classes
>>> import libraryname
>>> dir (libraryname)
>>> help (libraryname)
>>> help (libraryname.functionname)
*throughout the code, a library name can be shorted using the “as” (import library as lib)
*importing a function from a library is possible, (from library import function1)
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Modules for Cisco Infra.
- xmltodict: translates between XML-formatted files and python dictionaries
- json: translates between JSON-formatted files and python dictionaries
- PyYAML: translates between YAML formatted files and python dictionaries/lists
- pyang: a utility to verify YANG Modules
- requests: to interact with REST APIs and HTTP requests
- ncclient: to integrate with NETCONF
- netmiko: to initiate SSH connection to clients
- pysnmp: to interact with SNMP NMS, without APIs
- napalm: to function in a multivendor environments
- nornir: multithreaded framework with inventory management to work with large numbers of net devices
- unittest: to test the functionality of a python code
- pyats: to validate python codes for Cisco products (IaC)
- csv: to deal with excel spreadsheets as a data source imported in a python code
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
- Python Codes for Cisco
- refer to some python codes written to work on Cisco devices
- pythonex_ssh_ciscoRouter_iosXE_SHOW
- pythonex_ssh_ciscoRouter_iosXE_CONFIG
- pythonex_ssh_multiciscoRouter_iosXE_SHOW
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
https://iiinetworking.com || https://youtube.com/@iiinetworking || https://linkedin.com/company/iii-networking || info@iiinetworking.com
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )