28
Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

Embed Size (px)

Citation preview

Page 1: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

Introduction to Python

Kris KneubuhlerSENPUG July 17th 2014

Page 2: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Python 101 – Introduction

• Python Examples

• NXAPI Demo

• Q&A

Agenda

Page 3: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

© 2012 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 3

Python: the basics

Page 4: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Python is an interpreted programming (scripting) language– Available for Linux, Windows, Mac– Two common versions: 2.7(x) and 3.3(x)– 2.7 more widely used than 3.3 at the time of writing

• Python code is not compiled into standalone binary– It’s either interpreted (interactive shell) or translated into

byte code and executed by Python VM

• Code can be packaged as a “frozen binary” and executed on systems that don’t have Python installed– the Python VM is packaged within the frozen binary (using py2exe,

pyinstaller or freeze)

Basics

Page 5: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Python home page– http://www.python.org/

• Major Releases– Python 3.2.2 September 4, 2011– Python 3.1.4 June 11, 2011– Python 3.0.1 February 13, 2009– Python 2.7.2 June 11, 2011 – Python 2.6.7 June 3, 2011– Python 2.5.4 December 23, 2008– Python 2.4.6 December 19, 2008 – Python 2.3.7 March 11, 2008– Python 2.2.3 May 30, 2003– Python 2.1.3 April 8, 2002 – Python 2.0.1 June 2001– Python 1.6.1 September 2000

Python Distributions

2.7.x is probably the version most frequently used today; this slide deck focuses primarily on 2.7

Page 6: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Python is an interpreted language– no pre-compile step as in Java and C++– each time Python code is run it is interpreted afresh– code changes can be very quickly made and tested– code can also be entered interactively– can dynamically construct Python code

• For example in the form of a string and execute it directly

• What about performance?– (much) slower than compiled C/C++ .. but also much more flexible– Good enough for most cases

• Very large projects such as Openstack are implemented in Python

– Modules to measure (profile) performance exist

Python is interpreted

Page 7: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• When executing Python instructions, Python internally compiles the source into a format called byte code– This is meant to speed up execution

• This process is hidden from the programmer

• You will now and then notice .pyc files automatically created in your folders (depending if Python has write access)– Next time you run your code, assuming it hasn’t been modified,

Python skips the compilation step and directly runs the byte code inside the Python VM

• The Python VM is Python’s runtime engine. It always comes with any installation of Python– Note: VM does not mean a VMware VM here!

Byte code compilation

Page 8: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• If you are used to other programming languages that are compiled, you should know there is a significant difference in terms of error checking with interpreted languages

• Python checks errors at runtime

Interpreted code: error checking

Page 9: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Be aware that Python is case sensitive– A and a are different variables

– We’re going to explore variables in a bit

• Python programs typically have the .py extension– Run using python <code.py> or python –i <code.py>

Python is case-sensitive

Page 10: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• You MUST indent code blocks in Python– Keep this rule in mind, it will catch you almost inevitably if you are

already used to other programming languages

• There are no curly braces to delimitate code blocks

• Code blocks are identified with a colon and indentation

• Prefer white spaces to tabs for indentation– Four white spaces is the preferred de-facto standard– http://legacy.python.org/dev/peps/pep-0008/#indentation

Indentation is mandatory

Page 11: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• The hash # sign indicates comments follow– Usually ok for short comments– Can start a new line or be used at the end of a line

• Comments included at the beginning of your code appear when invoking help(yourscript):

Comments

Page 12: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Your code should contain comments

• They should be relatively short and to the point

• Comments should say why you are doing what you are doing

• The code already says how; why you did things in a certain way is more important

• Too many comments hurt readability though and require maintenance – find the right balance

Sidenote: should you write comments?

Page 13: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• If you are running Windows:– http://www.activestate.com/activepython/downloads– Download the “Community” edition

• If you are running Linux:– It should be available in your path already

• If you are running Mac OS-X:– It’s available natively. Start a terminal and type ‘python’– There is a also a DMG available at the Activepython URL listed

above

Where can I get Python?

Page 14: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• To write Python code, you need an editor that is aware of Python’s syntax and indentation:– Windows -- do not use Notepad or Wordpad. Try the free and open

source Notepad++ or the free and open source JEdit– Mac -- The built in TextEdit works, but not very well. Try the free

TextWrangler or the free and open source JEdit– Linux -- any unix text editor is fine, or try the above JEdit.

Getting a proper editor

Page 15: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• You can use a Python syntax-aware editor such as Notepad++ or vim or gedit and test all your code with python -i <code.py>– Try without the -i flag and see what the difference is

• Don’t forget to add the .py extension to your files to ensure the editor starts highlighting Python syntax

• Alternatively, there’s an easy to use, small and free IDE (Integrated Development Environment) called IDLE

• For larger projects, you can use Eclipse with PyDev, or PyCharm– There is a PyCharm module at end of this deck– For now, IDLE is good enough

How do I start Python

Page 16: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• IDLE is a simple IDE (integrated development environment)– Provides contextual help, command completion, syntax

highlighting, step-by-step debugging, etc.

• Simple and free– Distributed with Python since 1.5.x– Install Python and launch it now– It isn’t perfect, but it’s probably good enough for what we’re going to do

• Much more complex IDE:– PyDev inside Eclipse

IDLE

Page 17: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Launch IDLE and start coding! How about print “Hello World!” ?

• The print statement was directly interpreted – that is because you are sitting at the interpreter’s interactive prompt– Naturally, code can be saved in files rather than entered line by line– Try that as well and invoke the script using python –i <script.py>

Your very first Python statement

notice that parentheses inside print are not necessary in 2.7 (not true in 3.x!) there is no need for a semicolon (;) to end the print statement

Page 18: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• IDLE lets you directly enter Python commands interactively with immediate execution. You also get contextual command completion:

• You’ll pretty much never type code directly into the interactive shell though, except when testing/debugging

• Your code will live inside .py files

• IDLE can open .py files, run and help you debug your code

Exploring IDLE a bit further

Page 19: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Inside IDLE, go to File then select New Window

• This brings up a Python-aware editor that we are going to use to create our first program. You can also use a Python-friendly editor.

Your first program

Page 20: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Once inside the new window IDLE spawned, type this:

• Go to File, then Save As. Save your file and make sure you explicitly specify .py at the end of the name you provided

• If you press F5 now, Python will run your program in the main window

Your first program

Don’t worry about the keywords for now …

Page 21: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• If you’re using Windows, you can run .py files by double-clicking them or specifying how to run them:

• If we run our basic program, a black window will come and go very rapidly – we can trick Windows to keep the window from disappearing

Other ways of executing your program

Page 22: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Just add a input() statement at the end of your program to prevent Windows from closing the Python window after the script has executed

• You can also invoke the script with python -i (“dash i”)

A little trick for Windows users

Once you execute your program, input() prevents Windows from closing the window

Page 23: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Typing help() brings up interactive help. Type topics or keywords

• Outside of the interactive context, use help(‘keyword’)

• Alternatively, if you’re inside the interactive help context, just type while to get help on the while keyword

• To leave the interactive help session, type quit

Getting help

Page 24: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Literally every Python question you can come up with is answered on Stackoverflow http://stackoverflow.com/questions/tagged/python

• You can also subscribe to the Python Tutor mailing list https://mail.python.org/mailman/listinfo/tutor

• Or browse the official Python docs http://docs.python.org/2.7/

External help

Page 25: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• If you type help(‘this’), you’ll see these guiding principles:

“The Zen of Python”

Page 26: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

© 2012 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 26

Core data types

Page 27: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• Python provides several built-in data types:• Numbers: 1234, 3.1415, 3+4j, Decimal, Fraction• Strings: 'spam', “Joe's", b'a\x01c'• Lists: [1, [2, 'three'], 4]• Dictionaries: {'food': 'spam', 'taste': 'yum'}• Tuples: (1, 'spam', 4, 'U')• Files: myfile = open('eggs', 'r')• Sets: set('abc'), {'a', 'b', 'c'}• Other core types: Booleans, types, None

Data types

Page 28: Introduction to Python Kris Kneubuhler SE NPUG July 17 th 2014

• There is a significant difference in Python (much like in other languages) between the = and the == operator

• A single equal sign assigns a value to a named variable

• A double equal sign tests equality between the right-hand side and the left-hand side of the operation

Before we continue