Coding 1002 – Getting Started
with Python
Flo Pachinger, Developer Advocate
@flopachinger
DEVNET-1893.d
Cisco Webex Teams
Questions?
Use Cisco Webex Teams 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
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 3
What do we cover today?
• Why coding as a Network Engineer is important
• Python
• Interpreter
• Basic operators
• Conditionals, Functions and Loops
• Libraries and how to install them
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 4
Why Coding as a
Network Engineer?
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-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 6
What Changed?
API & Language Maturity
✓ RESTful APIs
✓ Expressive Modern Languages
Online Communities
✓ Open Source
✓ Social Code Sharing (GitHub)
✓ Public Package Repositories
You can get powerful things done with relatively small amounts of code!
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 7
Coding with Python
• Very popular programming
language
What is Python? • Free
• Huge Community
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
• Powerful
• Readable and easy to learn
Why Python for • Widely available and Open
Source
Network Engineers?
• Windows, Mac, Linux
• Routers & Switches
• Lots of training resources
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
• A Python Interpreter installed
on your system where you run
What do you need? the script
• Text editor
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
sample.py
How does Python
work?
Output
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
Let’s dive more into Python!
What python should I use?
• Python 3.x
• Python 2.7 will not be maintained past 2020
Check your python version
$ python -V
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
Using your Python Interpreter
How to… Command
Access the Python Interactive Shell $ python
Running a Python script $ python script.py
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 15
Python Script Structure and Execution
Import Modules
Functions
Output/Input
Variables
Conditionals & Loops
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
hello-world.py
Fun with Python
Basic 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-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 19
Numerical Operators
Math Operations >>> 5 + 2
7
Addition: + >>> 9 * 12
108
Subtraction: - >>> 13 / 4
Multiplication: * 3.25
>>> 13 // 4
Division: / 3
>>> 13 % 4
Floor Division: // 1
Modulo: % >>> 2 ** 10
1024
Power: **
DEVNET-1893.d © 2020 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 keyword >>> a
10
• Can contain: [A-Za-z0-9_-]
• Recommendations for naming (variables, >>> string_one = "Foo"
classes, functions, etc.) can be found in PEP8 >>> string_two = "Bar"
>>> new_string = string_one + string_two
Created with the = assignment operator >>> new_string
'FooBar'
Can see list of variables in the current
scope with dir()
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 21
Working with Strings
String Operations >>> "One" + "Two"
'OneTwo'
Concatenation: +
>>> "Abc" * 3
Multiplication: * 'AbcAbcAbc'
>>> "Hi, my name is {}!".format("Chris")
Some Useful String Methods 'Hi, my name is Chris!'
Composition: “{}”.format() >>> "a b c".split(" ")
['a’, 'b’, 'c']
Splitting: “”.split()
Joining: “”.join() >>> ",".join(['a’, 'b’, 'c'])
'a,b,c'
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 22
Basic I/O
Get Input with input() Display Output with print()
• Can pass multiple values
• Pass it a prompt string
• It will concatenate those values with
• It will return the user’s input as a string separators in between (default = spaces)
• You can convert the returned string to the • It will add (by default) a newline (‘\n’) to
data type you need int(), float(), etc. the end
>>> print(‘a’, ‘b’, ‘c’)
abc
>>> i = input(“Enter a Number: ”)
Enter a Number: 1
>>> int(i)
1
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 23
Python Conditionals & Loops
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-1893.d © 2020 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-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 26
Loops
Iterative Loops Conditional Loops
for individual_item in iterator: while logical_expression:
statements… statements…
>>> names = ["chris", "iftach", "jay"] >>> i = 0
>>> while i < 5:
>>> for name in names:
... print(i)
... print(name)
... i += 1
... ...
chris 0
iftach 1
jay 2
3
4
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 27
Python Functions
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)
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
Python Libraries
Python Libraries
sample.py
Library 1 Library 2 Library 3
Python Interpreter + Base Modules
Computing Hardware
© 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public
Importing and Using Packages & Modules
Import “other people’s” code into your >>> import requests
>>> requests.get('https://google.com')
script. <Response [200]>
Syntax:
import module >>> response = requests.get('https://google.com')
>>> response.status_code
from module import thing 200
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 32
PIP Installs Packages
• Included with Python v3+ (venv) $ pip install requests
Collecting requests
Coupled with a Python installation;
Downloading
may be called pip3 outside a venv <-- output omitted for brevity -->
Installing collected packages: idna, certifi, chardet, urllib3,
• Uses the open PyPI Repository requests
Python Package Index Successfully installed certifi-2018.4.16 chardet-3.0.4 idna-2.6
requests-2.18.4 urllib3-1.22
• Installs packages and their (venv) $
dependencies
• You can post your packages to PyPI!
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 33
Learning Outlook
• 1. Getting the basics done.
• Python Virtual Environments
• Work with various Libraries
• Python Classes
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 34
Continue your learning journey…
http://developer.cisco.com
• Programming fundamentals Learning Labs
https://developer.cisco.com/learning/modules/programming-fundamentals
• Learning Paths (Start Now)
https://developer.cisco.com/startnow/
• Reserve FREE Sandbox Environments
https://developer.cisco.com/site/sandbox/
DEVNET-1897 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 35
Complete your
online session
survey • Please complete your session survey
after each session. Your feedback
is very important.
• Complete a minimum of 4 session
surveys and the Overall Conference
survey (starting on Thursday) to
receive your Cisco Live t-shirt.
• All surveys can be taken in the Cisco Events Mobile
App or by logging in to the Content Catalog
on ciscolive.com/emea.
Cisco Live sessions will be available for viewing on demand after
the event at ciscolive.com.
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 36
Continue your education
Demos in the
Walk-In Labs
Cisco Showcase
Meet the Engineer
Related sessions
1:1 meetings
DEVNET-1893.d © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 37