Documente Academic
Documente Profesional
Documente Cultură
https://github.com/
CoPs for Programmers - Stack Overflow
https://stackoverflow.com/
CoPs for Programmers - Cisco DevNet
Cisco DevNet offers support to developers and
programmers who want to build Cisco-enable applications
or use Cisco APIs to enhance and manage their networks
https://developer.cisco.com
Start Python
Windows
C:\> python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Mac or Linux
$ python3
Python 3.5.2 (default, Aug 18 2017, 17:48:00)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Use Interactive Interpreter as a Calculator
$ python3
Python 3.5.2 (default, Aug 18 2017, 17:48:00)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 2+3
5
>>> 10-4
6
>>> 2*4
8
>>> 20/5
4
>>> 3**2
9
Use Interpreter to print Hello World
>>> "Hello World!"
• Strings can be 'Hello World!'
>>> 'Hello World!'
enclosed with single 'Hello World!'
quotes or double >>> print("Hello World!")
Hello World!
quotes.
• To remove the single
quotes in the output,
use the print
command.
Quit the Interpreter and Start IDLE
• Python includes the Windows
Integrated
Start > Python 3.6 > IDLE (Python 3.6
Development 32-bit).
Environment (IDLE)
• Windows - open IDLE Mac or Linux
from the Start menu >>> "Hello World!"
'Hello World!'
>>> 'Hello World!'
• Mac or Linux - open 'Hello World!’
IDLE from the >>> quit()
command line. $ idle3
IDLE Benefits
• Provides color
coding
• Includes a text
editor for writing
programs
• Quickly save and
run programs
Activity - Write, Save, and Run Your First Program
• Change the 2 to
increase or
decrease decimal
places.
Lists >>> hostnames=["R1","R2","R3","S1","S2"]
>>> type(hostnames)
• A list is an ordered <class 'list'>
>>> len(hostnames)
list of items. 5
>>> hostnames
• Create a list using the ['R1', 'R2', 'R3', 'S1', 'S2']
brackets [ ] and enclosing
each item in the list with
quotes.
• Use the type() command to
verify the data type.
• Use the len() command
return the number of items
in a list.
• Call the list variable name
to display it’s contents.
Lists >>> hostnames=["R1","R2","R3","S1","S2"]
>>> type(hostnames)
<class 'list'>
• Use the index to >>> len(hostnames)
5
refer to an item and >>> hostnames
manipulate the list ['R1', 'R2', 'R3', 'S1', 'S2']
>>> hostnames[0]
• The first item in a list is 'R1'
indexed as zero, the second is >>> hostnames[-1]
indexed as one, and so on. 'S2'
>>> hostnames[0]="RTR1"
• The last item can be >>> hostnames
referenced with index [-1] ['RTR1', 'R2', 'R3', 'S1', 'S2']
• Replace an item by assigning >>> del hostnames[3]
a new value to the index. >>> hostnames
['RTR1', 'R2', 'R3', 'S2']
• Use the del() command to >>>
remove an item from a list.
Dictionaries >>> ipAddress =
{"R1":"10.1.1.1","R2":"10.2.2.1","R3":"10.3.3
.1"}
• A list of unordered >>> type(ipAddress)
<class 'dict'>
key/value pairs
• Create a dictionary using
the braces { }
• Each dictionary entry
includes a key and a value.
• Separate key and values
with a colon.
• Use quotes for keys and
values that are strings.
Dictionaries >>> ipAddress =
{"R1":"10.1.1.1","R2":"10.2.2.1","R3":"10.3.3
.1"}
• Use the key to refer >>> type(ipAddress)
<class 'dict'>
to an entry >>> ipAddress
• The key is enclosed with {'R1': '10.1.1.1', 'R2': '10.2.2.1', 'R3':
brackets [ ]. '10.3.3.1'}
• Keys that are strings can be >>> ipAddress['R1']
referenced using single or '10.1.1.1’
double quotes. >>> ipAddress["S1"]="10.1.1.10"
>>> ipAddress
• Add a key/value pair by {'R1': '10.1.1.1', 'R2': '10.2.2.1', 'R3':
setting the new key equal to '10.3.3.1', 'S1': '10.1.1.10'}
a value. >>> "R3" in ipAddress
• Use key in dictionary True
command to verify if a key >>>
exist in the dictionary
Activity - Troubleshoot List and Dictionary Code
1. Open 02_list-dicts.py.
2. Run the code.
3. Troubleshoot the code until the script runs without
errors.
4. What errors did you fix in the script?
The Input Function
>>> firstName = input("What is your first
• The input() name? ")
What is your first name? Bob
function provides a >>> print("Hello " + firstName +"!")
way to get Hello Bob!
>>>
information from
the user.
Activity - Create a Script to Collect Personal
Information
1. Open a blank script file and save it in your GitHub
project directory as 03_personal-info.py.
2. Create a script that asks for four pieces of information
such as: first name, last name, location, and age.
3. Create a variable for a space: space = " "
4. Add a print statement that that combines all the
information in one sentence.
5. Run the script and troubleshoot any errors.
If/Else Function
• Open a blank script and nativeVLAN = 1
save it as 04_if-vlan.py. dataVLAN = 100
if nativeVLAN == dataVLAN:
• Create a simple if print("The native VLAN and the data VLAN
function that compares are the same.")
else:
two values and prints print("This native VLAN and the data VLAN
the results. are different.")
• Run the script and
troubleshoot any errors.
• Change the values to
test the else print
statement.
If/Elif/Else Function
• Open a blank script and aclNum = int(input("What is the IPv4 ACL
save it as 05_if-acl.py. number? "))
if aclNum >= 1 and aclNum <= 99:
• Create a more complex print("This is a standard IPv4 ACL.")
if function that takes elif aclNum >=100 and aclNum <= 199:
print("This is a extended IPv4 ACL.")
user input and includes else:
an elif loop. print("This is not a standard or extended
IPv4 ACL.")
• Note that the input
needs to be converted
to an integer.
For Loop
• A for loop iterates >>> devices=["R1","R2","R3","S1","S2"]
>>> for item in devices:
through items in a print(item)
list, dictionary, or
other sequenced R1
data type. R2
R3
• The variable name S1
“item” is arbitrary S2
>>>
and can be anything
the programmer
chooses.
For Loop with Embedded If
>>> for item in devices:
• Using an If loop if "R" in item:
print(item)
inside the For loop
R1
R2
R3
>>>
Use a For Loop to Create a New List
>>> switches=[]
• Create an empty >>> for item in devices:
if "S" in item:
list called switches. switches.append(item)
• API Server: The URL for the server that answers REST
requests
• Resources: Specifies the API that is being requested.
• Format: Usually JSON or XML
• Parameters: Specifies what data is being requested
API Documentation
• Use an Internet search
to find documentation
for an API.
API Documentation
• The API documentation
will specify...
• The request format (JSON, XML, or
text)
• The request parameters
• The response fields
JSON Response Data
http://api.open-notify.org/iss/v1/?lat=30.26715&lon=-97.74306
• None: The API resource is public and anybody can place the request.
• Basic HTTP: The username and password are passed to the server in an
encoded string.
• Token: A secret key generally retrieved from the Web API developer portal.
• Open Authorization (OAuth): An open standard for retrieving an access
token from an Identity Provider. The token is then passed with each API call.
Activity - Get Your MapQuest API Key
1. Go to: https://developer.mapquest.com/.
2. Click Sign Up at the top of the page.
3. Fill out the form to create a new account. For Company,
enter Cisco Networking Academy Student.
4. After clicking Sign Me Up, you are redirected to the Manage
Keys page.
5. Click Approve All Keys and expand My Application.
6. Copy your Consumer Key to Notepad for future use.
Importing Modules
import urllib.parse
• Open a blank script import requests
file and save it
as 08_parse-
json1.py.
• Import modules
Create Variables for API Request
Add the following variables to your script:
• main_api - the main URL that you are accessing
• orig - the parameter to specify your point of origin
• dest - the parameter to specify your destination
• key - the MapQuest API key you retrieved from the developer website
Combine the variables into the url variable using the urlencode
method to properly format the address variable
main_api = "https://www.mapquestapi.com/directions/v2/route?"
orig = "Washington"
dest = "Baltimaore"
key = "your_api_key"
url = main_api + urllib.parse.urlencode({"key": key, "from":orig, "to":dest})
Create the JSON Request
• Create a variable that json_data = requests.get(url).json()
print(json_data)
uses the get method
to request JSON data
from the submitted
URL.
• Print the results to
verify the request was
successful.
Activity - Test the URL Request
========== RESTART: /home/user/08_parse-json1.py ==========
1. Run your 08_json- {'route': {'distance': 38.089, 'hasHighway': True,
'hasUnpaved': False, 'hasAccessRestriction': False,
parse1.py script and 'options': {'mustAvoidLinkIds': [], 'maxWalkingDistance': -
1, 'manmaps': 'true', 'urbanAvoidFactor': -1,
verify it works. 'stateBoundaryDisplay': True, 'cyclingRoadFactor': 1,
'routeType': 'FASTEST', 'countryBoundaryDisplay': True,
2. Troubleshoot your 'drivingStyle': 2, 'highwayEfficiency': 22,
'narrativeType': 'text', 'routeNumber': 0,
code, if necessary. 'tryAvoidLinkIds': [], 'generalize': -1,
'returnLinkDirections': False, 'doReverseGeocode': True,
'avoidTripIds': [], 'timeType': 0, 'sideOfStreetDisplay':
3. You should get a True, 'filterZoneFactor': -1, 'walkingSpeed': -1,
similar JSON 'useTraffic': False, 'unit': 'M', 'tr
<output omitted>
response to what is >>>
shown here.
Print the URL and Check the Status of the JSON
Request
1. Save your script as 08_json-parse2.py.
2. Print the URL
3. Store the request status
4. Create an if loop that prints request status if statuscode is 0.
json_data = requests.get(url).json()
json_status = json_data["info"]["statuscode"]
if json_status == 0:
print("API Status: " + str(json_status) + " = A successful route call.\n")
Activity - Test Status and URL Print Commands
========== RESTART: /home/user/08_parse-json2.py ==========
1. Run your 08_json- URL:
https://www.mapquestapi.com/directions/v2/route?key=your_ap
parse2.py script i_key&from=Washington&to=Baltimore
API Status: 0 = A successful route call.
and verify it works.
>>>
2. Troubleshoot your
code, if necessary.
3. You should get a
similar output to
what is shown
here.
Add User Input for Address
1. Save your script as 08_json-parse3.py.
2. Delete the current orig and dest variables.
3. Rewrite the orig and dest to be within a while loop in which it
requests user input for the starting location and destination.
4. Be sure all the remaining code is indented within the while loop.
while True:
orig = input("Starting Location: ")
dest = input("Destination: ")
url = main_api + urllib.parse.urlencode({"key": key, "from":orig, "to":dest})
print("URL: " + (url))
Activity - Test User Input
========== RESTART: /home/user/08_parse-json3.py ==========
1. Run your 08_json- Starting Location: Washington
Destination: Baltimore
parse3.py script URL:
https://www.mapquestapi.com/directions/v2/route?key=your_ap
and verify it works. i_key&from=Washington&to=Baltimore
API Status: 0 = A successful route call.
2. Troubleshoot your Starting Location: <Ctrl+C>
code, if necessary. >>>
what is shown
here.
Displaying Trip Data
The final application prints the values for
the distance, formattedTime, and
fuelUsed keys from the route dictionary.
Starting Location: Washington
Destination: Baltimore
URL:
https://www.mapquestapi.com/directions/v2/route?to=Balti
more&key=Your_api_key&from=Washington
API Status: 0
Starting Location: q
>>>
Check for Invalid User Input
1. Save your script as 08_json-parse7.py.
2. The final step is to finish the if loop to respond to the user when the
json_status does not equal 0.
3. The most common error will most likely be for invalid location entries.
4. Create a elif function that checks for json_status = 402 and display a
message, as shown here.
if json_status == 0:
.
.
.
elif json_status == 402:
print("**********************************************")
print("For Staus Code: " + str(json_status) + "; Invalid user inputs for one or both locations.")
print("**********************************************\n")
print("=============================================")
Check for Other Error Types
Invalid user inputs is only one error type.
You could write code to display error messages for other common
errors.
For this application, add an else statement that ends the if loop and
covers all other json_status values, as shown here.
elif json_status == 402:
print("**********************************************")
print("For Staus Code: " + str(json_status) + "; Invalid user inputs for one or both locations.")
print("**********************************************\n")
print("=============================================")
else:
print("************************************************************************")
print("For Staus Code: " + str(json_status) + ", Refer to:")
print("https://developer.mapquest.com/documentation/directions-api/status-codes")
print("************************************************************************\n")
Activity - Test Full Application Functionality
****************************************************************
Status Code: 402; Invalid user inputs for one or both locations.
****************************************************************
************************************************************************
Status Code: 602; Refer to:
https://developer.mapquest.com/documentation/directions-api/status-codes
************************************************************************
************************************************************************
Status Code: 611; Refer to:
https://developer.mapquest.com/documentation/directions-api/status-codes
************************************************************************