Python3 Theory
Python3 Theory
Comments
Ironically, the first thing we're going to do is show how to tell a computer to ignore a part of a program. Text written in a program but not run by the computer is called
a comment. Python interprets anything after a # as a comment.
Comments can:
# This variable will be used to count the number of times anyone tweets the word persnickety
persnickety_count = 0
# This code will calculate the likelihood that it will rain tomorrow
complicated_rain_calculation_for_tomorrow()
Ignore a line of code and see how a program will run without it:
# useful_value = old_sloppy_code()
useful_value = new_clean_code()
2 PRINT
Now what we're going to do is teach our computer to communicate. The gift of speech is valuable: a computer can answer many questions we have about "how" or "why" or
"what" it is doing. In Python, the print() function is used to tell a computer to talk. The message to be printed should be surrounded by quotes:
In the above example, we direct our program to print() an excerpt from a notable book. The printed words that appear as a result of the print() function are referred to
as output. The output of this example program would be:
Programming languages offer a method of storing data for reuse. If there is a greeting we want to present, a date we need to reuse, or a user ID we need to remember we can
create a variable which can store a value. In Python, we assign variables by using the equals sign (=).
In the above example, we store the message "Hello there" in a variable called message_string.
Variables can't have spaces or symbols in their names other than an underscore (_). They can't begin with numbers but they can have numbers after the first letter
(e.g., cool_variable_5 is OK).
It's no coincidence we call these creatures "variables". If the context of a program changes, we can update a variable but perform the same logical process on it.
# Greeting
message_string = "Hello there"
print(message_string)
# Farewell
message_string = "Hasta la vista"
print(message_string)
Above, we create the variable message_string, assign a welcome message, and print the greeting. After we greet the user, we want to wish them goodbye. We then
update message_string to a departure message and print that out.
4. ERRORS
Humans are prone to making mistakes. Humans are also typically in charge of creating computer programs. To compensate, programming languages attempt to understand
and explain mistakes made in their programs.
Python refers to these mistakes as errors and will point to the location where an error occurred with a ^ character. When programs throw errors that we didn't expect to
encounter we call those errors bugs. Programmers call the process of updating the program so that it no longer produces unexpected errors debugging.
Two common errors that we encounter while writing Python are SyntaxError and NameError.
SyntaxError means there is something wrong with the way your program is written — punctuation that does not belong, a command where it is not expected, or a missing
parenthesis can all trigger a SyntaxError.
A NameError occurs when the Python interpreter sees a word it does not recognize. Code that contains something that looks like a variable but was never defined will throw
a NameError.
Example:
print('This message has mismatched quote marks!") #nameerror
print(Abracadabra) #syntaxerror
5. Python Data Type
You can get the data type of any object by using the type() function
Example:
6. Python Strings
String literals in python are surrounded by either single quotation marks, In Python a string is either surrounded by double quotes ("Hello world") or
or double quotation marks. single quotes ('Hello world'). It doesn't matter which kind you use, just be
consistent.
'hello' is the same as "hello".
Example:
print("Hello")
print('Hello’)
a = "Hello"
print(a)
There are three numeric types in Python: containing one or more decimals.
x = 1.10
int y = 1.0
z = -35.59
float print(type(x))
print(type(y))
complex print(type(z))
Examples Complex numbers are written with a "j" as the imaginary part:
Example 1:
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example 2:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
9 Python Operators
x = ["CCNA", "CCNP"]
print("CCNA" in x)
# returns True because a sequence with the value "CCNA" is in the list
x = ["CCNA", "CCNP"]
print("CCIE" not in x)
# returns True because a sequence with the value "CCIE" is not in the list
10 Python Lists
Tuple Length
Range of Negative Indexes To determine how many items a tuple has, use the len() method:
Specify negative indexes if you want to start the search from the end of the tuple: Example:
Example: thistuple = ("apple", "banana", "cherry")
This example returns the items from index -4 (included) to index -1 (excluded) print(len(thistuple))
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
12 Python Sets
Set Add multiple items to a set, using the update() method:
A set is a collection which is unordered and unindexed. In Python sets are written with curly thisset = {"apple", "banana", "cherry"}
brackets. thisset.update(["orange", "mango", "grapes"])
Example: print(thisset)
thisset = {"apple", "banana", "cherry"}
print(thisset)
Note: Sets are unordered, so you cannot be sure in which order the items will appear. Get the Length of a Set
thisset = {"apple", "banana", "cherry"}
Example
Check if "banana" is present in the set: thisset = {"apple", "banana", "cherry"}
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset) thisset.discard("banana")
print(thisset)
Change Items Note: If the item to remove does not exist, discard() will NOT raise an error.
Once a set is created, you cannot change its items, but you can add new items.
Join Two Sets
Add Items set1 = {"a", "b" , "c"}
To add one item to a set use the add() method. set2 = {1, 2, 3}
To add more than one item to a set use the update() method.
Example: set3 = set1.union(set2)
thisset = {"apple", "banana", "cherry"} print(set3)
thisset.add("orange")
print(thisset)
Note: You can use the union() method that returns a new set containing all items from both sets,
or the update() method that inserts all the items from one set into another:
13 Python Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are if "model" in thisdict:
written with curly brackets, and they have keys and values. print("Yes, 'model' is one of the keys in the thisdict dictionary")
Example:
thisdict = {
"brand": "Ford", Dictionary Length
"model": "Mustang", Example:
"year": 1964 print(len(thisdict))
}
print(thisdict)
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Accessing Items Example:
You can access the items of a dictionary by referring to its key name, inside square brackets: myfamily = {
Example: "child1" : {
x = thisdict["model"] "name" : "Emil",
There is also a method called get() that will give you the same result: "year" : 2004
Example: },
x = thisdict.get("model") "child2" : {
"name" : "Tobias",
"year" : 2007
Change Values },
You can change the value of a specific item by referring to its key name: "child3" : {
Example: "name" : "Linus",
thisdict = { "year" : 2011
"brand": "Ford", }
"model": "Mustang", }
"year": 1964
}
thisdict["year"] = 2018 Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example:
Check if Key Exists thisdict = {
"brand": "Ford",
"model": "Mustang",
Example: "year": 1964
thisdict = { }
"brand": "Ford", thisdict["color"] = "red"
"model": "Mustang", print(thisdict)
"year": 1964
}
14. Python Casting
my_function()
Arguments
Information can be passed into functions as arguments. Arbitrary Arguments, *args
Arguments are specified after the function name, inside the parentheses. You can add as many If you do not know how many arguments that will be passed into your function, add a * before
arguments as you want, just separate them with a comma. the parameter name in the function definition.
The following example has a function with one argument (arg). def my_function(*network):
Example: print("this is youngest " + network[1])
def my_function(arg): my_function("ccna", "ccnp", "ccie")
print(arg + " NETWORKING“)
my_function("CCNA")
my_function("CCNP") Arbitrary Keyword Arguments, **kwargs
my_function("CCIE") If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition.
def my_function(**network):
print("This is network program " + network["intermediate"])
my_function(basic = "CCNA", intermediate = "CCNP")
19. Python Modules
What is a Module? Built-in Modules
Consider a module to be the same as a code library. There are several built-in modules in Python, which you can import whenever you like.
A file containing a set of functions you want to include in your application. import platform
x = platform.system()
print(x)
Step#1: Create a Module
To create a module just save the code you want in a file with the file extension .py:
Import From Module:
The module named mymodule has one function and one dictionary:
mymodule.py mymodule.py
def greeting(name):
print("Hello, " + name)
import mymodule
mymodule.greeting("NETWORK AUTOMATION")
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):
mymodule.py
Use a module
20. Python RegEx
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. import re
RegEx can be used to check if a string contains the specified search pattern. txt = "The rain in Spain“
x = re.findall("ai", txt)
print(x)
RegEx Module
Python has a built-in package called re, which can be used to work with Regular
Expressions. The search() Function
The search() function searches the string for a match, and returns a Match object if there is
a match.
Import the re module:
import re If there is more than one match, only the first occurrence of the match will be returned:
RegEx in Python
When you have imported the re module, you can start using regular expressions: The search() Function
The search() function searches the string for a match, and returns a Match object if there is
a match.
If there is more than one match, only the first occurrence of the match will be returned:
import re
txt = "The rain in Spain“
x = re.search("r", txt)
print(“The first white-space character is located in position:", x.start())
Install PIP
If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/
Download a Package
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install
netmiko
Using a Package
22. Python Try Except (Error Handling)
The try block lets you test a block of code for errors. Finally
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except
blocks. The finally block, if specified, will be executed regardless if the try block raises an error
or not.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
These exceptions can be handled using the try statement:
try:
print(x)
except:
print("An exception occurred")
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a
special block of code for a special kind of error:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
23. Python User Input
The json.dumps() method has parameters to make it easier to read the result:
Example:
json.dumps(x, indent=4)
Example:
import json
x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
# use four indents to make it easier to read the result:
print(json.dumps(x, indent=4))