0% found this document useful (0 votes)
55 views

Devnet 2893

Uploaded by

LAngel Reyes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Devnet 2893

Uploaded by

LAngel Reyes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

DEVNET-2893

Coding 1002: Intro Python

Denise Kwan – Developer Advocate & Support


Agenda
• Why Python?
• Using the Python Interpreter
• Basic Python Syntax
• Collections and Loops
• Script Structure and Execution

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

>>> do(“repetitious work…”) request


Done.

response OK!

 Request actions be performed


 Get information
 Store information

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.

for switch in my_network:


for interface in switch:
if interface.is_down() and interface.last_change() > thirty_days:
interface.shutdown()
interface.set_description("Interface disabled per Policy")

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]>

 Social Code Sharing (GitHub)


 Public Package Repositories

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

• Power and Flexibility


Create & Work With: Shell Scripts, Back-end Web APIs, Databases, Machine Learning, …

• 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

 Text Files (UTF-8)


 May contain Unicode
Some editors / terminals
don’t support Unicode
 Use any Text Editor
Using a Python-aware editor
will make your life better
 No Need to Compile Them

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

 The activation script will modify your prompt.


 Inside a virtual environment your interpreter will always be `python`.

•$ 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) $

• You can post your packages to


PyPI!

DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 15
Using your Python Interpreter

How to… Command

Access the Python Interactive Shell $ python

Running a Python script $ python script.py

Running a script in ‘Interactive’ mode $ python -i script.py


Execute the script and then remain in the Interactive Shell

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’>

int -128, 0, 42 >>> type(1.4)


<class ‘float’>
float -1.12, 0, 3.14159
>>> type(True)
bool True, False <class ’bool’>

str “Hello 😎” >>> type("Hello")


Can use ‘’, “”, and “””””” <class ’str’>

bytes b”Hello \xf0\x9f\x98\x8e” >>> type(b"Hello")


<class ‘bytes’>

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

• Can contain: [A-Za-z0-9_-] >>> string_one = "Foo"


• Recommendations for naming >>> string_two = "Bar"
(variables, classes, functions, etc.) >>> new_string = string_one + string_two
>>> new_string
can be found in PEP8
'FooBar'
Created with the = assignment
operator
Can see list of variables in the
current scope with dir()

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

Check an object’s type with type(object)


Look inside an object with dir(object)

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'

>>> "Hi, my name is {}!".format("Chris")


Some Useful String Methods 'Hi, my name is Chris!'
Composition: “{}”.format()
>>> "a b c".split(" ")
Splitting: “”.split() ['a’, 'b’, 'c']
Joining: “”.join()
>>> ",".join(['a’, 'b’, 'c'])
'a,b,c'

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

>>> print(‘a’, ‘b’, ‘c’)


a b c

>>> i = input(“Enter a Number: ”)


Enter a Number: 1
>>> int(i)
1

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

Name Notes Example


type()

list • Ordered list of items [‘a’, 1, 18.2]


• Items can be different data types
• Can contain duplicate items
• Mutable (can be changed after created)
tuple • Just like a list; except: (‘a’, 1, 18.2)
• Immutable (cannot be changed)
dictionary • Unordered key-value pairs {“apples”: 5,
dict • Keys are unique; must be immutable “pears”: 2,
• Keys don’t have to be the same data type “oranges”: 9}
• Values may be any data type

DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 29
Working with Collections

Name Creating Accessing Updating


type() Indexing
list l = [‘a’, 1, 18.2] >>> l[2] >>> l[2] = 20.4
18.2 >>> l
[‘a’, 1, 20.4]

tuple t = (‘a’, 1, 18.2) >>> t[0] You cannot update tuples after they have been
‘a’ created.

dict d = {“apples”: 5, >>> d[“pears”] >>> d[“pears”] = 6


“pears”: 2, 2 >>> d
“oranges”: 9} {“apples”: 5, “pears”: 6, “oranges”:
9}

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}

{}.items() >>> d.items()


dict_items([('a’,1), ('b’,2), ('c',3)])
{}.keys()
>>> d.keys()
{}.values() dict_keys(['a’, 'b’, 'c’])

>>> 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

Don’t forget: Cisco Live sessions will be available for viewing


on demand after the event at ciscolive.cisco.com

DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 43
Continue Your Education

Demos in Meet the Related


Walk-in
the Cisco engineer sessions
self-paced
Showcase labs 1:1
meetings

DEVNET-2893 © 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public 44
Thank you

You might also like