Devnet 2893
Devnet 2893
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 3
learninglabs.cisco.com/modules/intro-python
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 4
The Value-Proposition for APIs
response OK!
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 5
“It’s a way for two pieces of software to
talk to each other”
Application Programming Interface (API)
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 6
The Value-Proposition for Programmability
Coding is the process of writing down instructions, in a language a
computer can understand, to complete a specific task.
Q: What task?
A: Your task.
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 7
What Changed?
API & Language Maturity $ pip install requests
Collecting requests
RESTful APIs Using cached
<-- output omitted for brevity -->
Expressive Modern Languages $ python
>>> import requests
Online Communities >>> requests.get("https://api.github.com")
Open Source <Response [200]>
You can get powerful things done with relatively small amounts of code!
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 8
Why Python?
• Domain Applicability
Established online DevOps Community
• Platform Flexibility
Run Your Code: Laptop, Server, VM, Container, Cloud, Cisco IOS Device
• We Like It!
We have: Laptop Stickers, T-Shirts, Social Profiles, and Emotional Connections to Our
Code
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 9
Python Scripts
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 10
Using a Python
Interpreter
Know Thy Interpreter
What interpreter are you using? What version is it?
python $ python -V
python2
python3
python3.5 Where is it?
python3.6 $ where command
other
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 12
What is a Virtual Environment?
Directory Structure $ python3 -m venv venv
$
Usually associated with a $ tree -L 1 venv/
venv/
Project ├── bin
├── include
An isolated environment for ├── lib
installing and working with └── pyvenv.cfg
Python Packages $
$ source venv/bin/activate
(venv) $
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 13
Activating a Python Virtual Environment
source environment-name/bin/activate
•$ source venv/bin/activate
•(venv) $
•(venv) $
•(venv) $ deactivate
•$
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 14
PIP Installs Packages
• Included with Python v3+ (venv) $ pip install requests
Collecting requests
Coupled with a Python installation;
may be called pip3 outside a venv Downloading
<-- output omitted for brevity -->
• Uses the open PyPI Repository Installing collected packages: idna,
certifi, chardet, urllib3, requests
Python Package Index
Successfully installed certifi-
• Installs packages and their 2018.4.16 chardet-3.0.4 idna-2.6
requests-2.18.4 urllib3-1.22
dependencies (venv) $
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 15
Using your Python Interpreter
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 16
Python’s Interactive Shell
Accepts all valid Python statements
Use It To:
To Exit:
Play with Python syntax Ctrl + D or exit()
Incrementally write Code
Play with APIs and Data
(venv) $ python
Python 3.6.5 (default, Apr 2 2018, 15:31:03)[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on
linuxType "help", "copyright", "credits" or "license" for more information.
>>>
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 17
Basic Python Syntax
Basic Data Types
Python Values >>> type(3)
type() (examples) <class ‘int’>
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 19
Numerical Operators
Math Operations >>> 5 + 2
7
Addition: + >>> 9 * 12
Subtraction: - 108
>>> 13 / 4
Multiplication: * 3.25
>>> 13 // 4
Division: /
3
Floor Division: // >>> 13 % 4
1
Modulo: %
>>> 2 ** 10
Power: ** 1024
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 20
Variables
Names >>> b = 7
>>> c = 3
• Cannot start with a number [0-9] >>> a = b + c
• Cannot conflict with a language >>> a
keyword 10
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 21
In Python, Everything is an Object!
Use . (dot) syntax to access >>> a = 57
>>> a.bit_length()
“things” inside an object. 6
>>> "WhO wRoTe THIs?".lower()
'who wrote this?'
Terminology
When contained inside an object, we
call…
Variable Attribute
Function Method
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 22
Working with Strings
String Operations >>> "One" + "Two"
'OneTwo'
Concatenation: +
Multiplication: * >>> "Abc" * 3
'AbcAbcAbc'
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 23
Basic I/O
Get Input with input() Display Output with print()
• Pass it a prompt string • Can pass multiple values
• It will return the user’s input as a string • It will concatenate those values with
separators in between (default =
• You can convert the returned string to spaces)
the data type you need int(), float(), • It will add (by default) a newline (‘\n’)
etc. to the end
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 24
Conditionals
Syntax: Comparison Operators:
if expression1:
Less than <
statements…
elif expression2: Greater than >
statements… Less than or equal to <=
else:
statements… Greater than or equal to >=
Equal ==
Indentation is important!
Not Equal !=
4 spaces indent recommended Contains element in
You can nest if statements Combine expressions with: and, or
Negate with: not
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 25
Conditionals | Examples
>>> b = 5 >>> words = "Foo Bar"
>>> if b < 0: >>> if "Bar" in words:
... print("b is less than zero") ... print("words contains 'Bar'")
... elif b == 0: ... elif "Foo” in words:
... print("b is exactly zero") ... print("words contains 'Foo'")
... elif b > 0: ...
... print("b is greater than zero") words contains 'Bar'
... else:
... print("b is something else")
...
b is greater than zero
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 26
Functions | Don’t Repeat Yourself
Modularize your code >>> def add(num1, num2):
... result = num1 + num2
• Defining your own Functions ... return result
...
• (optionally) Receive arguments
>>>
• (optionally) Return a value >>> add(3, 5)
8
Syntax:
def function_name(arg_names): >>> def say_hello():
statements… ... print("Hello!")
>>>
return value
>>> say_hello()
... Hello!
function_name(arg_values)
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 27
Python Collections and
Loops
Data Structures / Collection Data Types
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 29
Working with Collections
tuple t = (‘a’, 1, 18.2) >>> t[0] You cannot update tuples after they have been
‘a’ created.
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 30
Dictionary Methods
Some useful dictionary methods: >>> d = {"a": 1, "b": 2, "c": 3}
>>> d.values()
dict_values([1, 2, 3])
There are many more! 😎
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 31
Loops
Iterative Loops Conditional Loops
for individual_item in while logical_expression:
iterator:
statements… statements…
>>> names = ["chris", "iftach", "jay"] >>> i = 0
>>> for name in names: >>> while True:
... print(name) ... print(i)
... ... i += 1
chris ...
iftach 0
jay 1
2
3
4
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 32
Unpacking
Q: What if you wanted to break >>> a, b, c = [1, 2, 3]
>>> a
out a collection to separate 1
variables? >>> b
2
>>> c
3
A: Unpack them!
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 33
Iterating through a Dictionary
• Use the dictionary .items() method, Method returns
which returns a “list of tuples” dictionary items as a list
• Unpack each tuple into variable of (key, value) tuples,
names of your choosing to use within which the for loop will
your block of statements iteratively unpack into
your variable names.
>>> for fruit, quantity in fruit.items():
... print("You have {} {}.".format(quantity, fruit))
...
You have 5 apples.
You have 2 pears.
You have 9 oranges.
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 34
Got more questions? Come find me!
• [email protected]
• @Kareem_Isk
• http://github.com/kiskander
• @CiscoDevNet
• facebook.com/ciscodevnet/
• http://github.com/CiscoDevNet
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 41
Cisco Webex Teams
Questions?
Use Cisco Webex Teams (formerly Cisco Spark)
to chat with the speaker after the session
How
1 Find this session in the Cisco Events Mobile App
2 Click “Join the Discussion”
3 Install Webex Teams or go directly to the team space
4 Enter messages/questions in the team space
cs.co/ciscolivebot#DEVNET-2893
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 42
Complete your online
session survey
• Please complete your Online Session
Survey after each session
• Complete 4 Session Surveys & the Overall
Conference Survey (available from
Thursday) to receive your Cisco Live T-
shirt
• All surveys can be completed via the Cisco
Events Mobile App or the Communication
Stations
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 43
Continue Your Education
DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 44
Thank you