Practical Python Programming: Charlene - Nielsen@Ualberta - Ca May 23Rd and 24Th, 2013 9:00 A.M. To 12:00 Noon Biosci B118
Practical Python Programming: Charlene - Nielsen@Ualberta - Ca May 23Rd and 24Th, 2013 9:00 A.M. To 12:00 Noon Biosci B118
[email protected]
May 23rd and 24th, 2013
9:00 a.m. to 12:00 noon
BioSci B118
Practical Python Programming
B118 Computer Access
1. Boot the machine in the Windows operating system
2. To access the internet: AUTHENTICATE
using your CCID and password
3. Right-click on the START button to ‘Explore All Users’
4. Navigate to the WORKSPACE directory on the C drive
5. In a web browser, download the following to
C:\WORKSPACE from: bit.ly/ppp-zip
6. Extract all/Unzip ppp.zip in to C:\Workspace\ppp
7. Open the pdf files and resize the PDF reader window
to fit part of the monitor screen
Outline
• Graphics
• Financial
• Science
http://wiki.python.org/moin/OrganizationsUsingPython
Who uses it?
• Electronic Design Automation
• Software Development
• Education
• Business Software
• Government
http://wiki.python.org/moin/OrganizationsUsingPython
Who is responsible for Python?
• Created by Guido van Rossum
– born 31 Jan 1956 (Netherlands)
– currently works at Google (since 2005)
More history:
http://docs.python.org/release/2.6.5/license.html
http://en.wikipedia.org/wiki/History_of_Python
When to (not) use it?
• PRO: Suitable for everyday tasks,
therefore minimizing the amount of time a
programmer spends on a project
http://wiki.python.org/moin/Python2orPython3
What can it do?
And
Run Web sites more! Build test suites for
C or Java code
Write GUI
interfaces
Process large
XML data sets
Control number-
crunching code on
supercomputers Make a commercial
application scriptable
by embedding the
Python interpreter
inside it
http://www.headfirstlabs.com/books/hfpython/
Where can it be found?
• www.python.org Follow the easy online
installation instructions!
• https://www.enthought.com/products/canopy/
academic/
– Linux/Unix
– OS/2
– Mac
– Amiga
Note: ‘import antigravity’ only works in version 3.x, print statement is from 2.x
http://xkcd.com/353/
Why use it?
• Programmability
– Wide range of readymade libraries that can be (freely!) used in
your own programs; i.e. “batteries included”
– Supports, but doesn't force, object-oriented programming (OOP)
– Integration with other languages (e.g. Java, C)
www.pycon.org
www.scipy.org
How can it be used?
• Scripting
– ‘gluing’ together commands for other software applications
• Programming
– text processing, web site development, email, scientific computing
www.devsource.com/c/a/Languages/More-Than-Five-Things-You-Didnt-Know-You-Could-Do-With-Python/
• Python does COM
• Python does .NET
• Python does Java better than Java
• Python is high-performance
• Python talks to hardware
• Education
– MIT and other institutions use Python as the programming
language in their introductory computer science courses
How can it be learned?
• Official Python tutorial
http://docs.python.org/release/2.6.5/tutorial/index.html
• Hands-on now!
Easy environments
• Command line
– The interpreter
• IDE (IDLE):
Integrated
DeveLopment
Environment
– Interactive window
– Script window
• Other software
(not used in this workshop)
The Python Interpreter
We’re going to skip the command line, and go on to…
IDLE for Python in B118
Click the START button
> PROGRAMS
> ARCGIS
> PYTHON 2.6
> IDLE (PYTHON GUI)
We are using the ArcGIS default installation of the Integrated DeveLopment Environment because it is
readily available for GIS development. Many other IDEs (discussed later) are available for your use,
but this one makes interacting with ArcGIS easy breezy.
IDLE: Interactive window
http://docs.python.org/library/idle.html
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
Interactive window menu: File
Open an existing module
Create a new editing window (searches sys.path)
Open an existing file Show classes and methods
Open a list of recent files in current file
Show sys.path directories,
modules, classes and
Save current window to the methods
associated file (unsaved
windows have a * before
Save current window to new
and after the window title)
file, which becomes the
associated file
Save current window to
different file without Print the current window
changing the associated file
Close current window (asks
to save if unsaved)
Close all windows, quit
(asks to save if unsaved)
Interactive window menu: Edit 1
Undo last change to current
window (A maximum of
1000 changes may be
undone) Redo last undone change to
current window
Shell and Debug menus are not available in the script window
Interactive window menu: G.T.K.*
Open a configuration dialog. Fonts, indentation,
keybindings, and color themes may be altered. Startup
Preferences may be set, and Additional Help Sources
can be specified. On MacOS X this menu is not
present, use menu 'IDLE > Preferences...' instead.
itsraining =
False
Programming primer
• Indentation and whitespace required
– Leading whitespace (i.e. spaces) at the beginning of a
logical line is used to compute the indentation level of the line,
which in turn is used to determine the grouping of statements
– Trailing whitespace is ignored
– All lines you want grouped together must be indented
identically!
thesunshines = True
while thesunshines:
{(No
print “Skip work and go to the beach”
BEGIN/END
or braces)} thesunshines = False
Programming primer
• Comments
– Helps explain what the code is doing
– Ignored when executed
– Two ways to indicate comments:
# type comment here
“““ type comment here ”””
>>> help(‘print’)
http://docs.python.org/reference/lexical_analysis.html
Literals
• Notations for constant values of some
built-in types (i.e. the stuff you type directly)
– Numeric = plain integers, long integers,
floating point numbers, and imaginary numbers
– Strings = text
enclosed in ‘single quotes’ or “double quotes”
help(‘STRINGS')
help(‘NUMBERS’)
Variables
• A name that represents or refers to a value
(i.e. the stuff you want stored for various uses)
– Dynamic – no need to define the type up front
– Created through an assignment statement that gives them
values using the ‘=’ operator
– If you don’t have an assignment (i.e. a name to the left of the ‘=’)
then Python stores it in the default result variable ‘_’
(note: type ‘_’ at the command prompt to view current value)
“Programmers use these variable names to make their code read more
like English, and because they have lousy memories. If they didn’t use
good names for things in their software, they’d get lost when they tried
to read their code again.”
(“Learn Python the Hard Way” by Zed Shaw)
Operators
• Tokens that work with or operate on values
• Includes:
– Arithmetic
– Assignment
– Comparison
– Bitwise
– Logical
– Membership
– Identity
(Note: The smaller-font ones are not included in the next set of slides; look them up in the help!)
help('OPERATORS')
http://www.tutorialspoint.com/python/python_basic_operators.htm
Operators: Arithmetic
+ Add (Note: Concatenation when used with strings)
- Subtract
/ Divide
Shell and Debug menus are not available in the script window
But, all the previously shown ones are: File, Edit, Windows, Help!
Run menu is not available in the interactive window
Script window menu: Format
Shift selected lines right 4 spaces
http://docs.python.org/release/2.6.5/reference/compound_stmts.html
if
• The if statement is used for conditional execution, a.k.a.
testing values and making decisions
http://docs.python.org/release/2.6.5/reference/compound_stmts.html
if
• Generic syntax:
if expression: Most basic
statement(s) minimum coding
elif expression:
statement(s)
else:
statement(s)
http://docs.python.org/release/2.6.5/reference/compound_stmts.html
while
• The while statement is used for repeated execution as
long as an expression is true
• Generic syntax:
while expression:
statement(s)
http://docs.python.org/release/2.6.5/reference/compound_stmts.html
for
• The for statement is used to iterate over the elements of a
sequence (such as a string, tuple or list) or other iterable object
• Generic syntax:
for iterating_var in sequence:
statements(s)
http://docs.python.org/release/2.6.5/reference/compound_stmts.html
Now try this…
• Type the following in the script window:
>>> # if
abs(x) globals()
bin(x) help([object])
cmp(x, y) hex(x)
complex([real[, imag]]) id(object)
dict([arg]) input([prompt])
dir([object]) int([x[, base]])
divmod(a, b) isinstance(object, classinfo)
enumerate(sequence[, start=0]) iter(o[, sentinel])
eval(expression[, globals[, locals]]) len(s)
file(filename[, mode[, bufsize]]) list([iterable])
float([x]) locals()
format(value[, format_spec]) long([x[, base]])
• Generic syntax:
def functionname( parameters ):
Required """function_docstring"""
keyword: def function_suite
defines the return [expression]
function
Modules
• Basically, subprograms that define things,
e.g. functions, classes, variables
• Built-in (as opposed to user-defined) modules
are also called standard libraries
http://docs.python.org/release/2.6.5/library
http://www.doughellmann.com/PyMOTW/
Modules
• Different ways to grab these extra tools:
1. import <module name>
• Requires module name as prefix to tools
e.g. import random
randvalue = random.random() * 100
Certainly, sir.
What would
you like?
Error handling
• As with all things and in Python, it’s
Easier to Ask Forgiveness
than Permission
i.e. try and perform an operation; if all goes well, great;
if not, ask for forgiveness…
4. IDLE is often good for quick jobs (and has some useful
tools)
• Software Carpentry:
http://software-carpentry.org
http://www.python.org/community/sigs/current/edu-sig/
E-resources
(online links to software, documentation, free books, tutorials, sample code, and articles)
• http://www.python.org/
• http://hetland.org/writing/instant-python.html
• http://rgruet.free.fr/PQR26/PQR2.6.html
• http://diveintopython.org/
• http://www.headfirstlabs.com/books/hfpython/
• http://learnpythonthehardway.org/
• http://greenteapress.com/thinkpython/
• http://homepage.mac.com/s_lott/books/python.html
• http://www.tutorialspoint.com/python/
• http://www.developer.com/lang/other/article.php/3624681/Python-Tutorial-Index-Page.htm
• http://www.swaroopch.com/notes/Python
• http://www.korokithakis.net/tutorials/python
• http://oreilly.com/python/
• http://en.wikipedia.org/wiki/Comparison_of_programming_languages
• http://code.activestate.com/recipes/langs/python/
• http://pypi.python.org/pypi
• http://www.python.org/doc/humor/
UofA e-books
(subscription is accessible through an on-campus computer with a UofA IP address or CCID login)
http://www.springerlink.com/
• Pro Python, Marty Alchin
• Python Programming Fundamentals, Kent D. Lee
• A Primer on Scientific Programming with Python, Hans Petter Langtangen
• Python Scripting for Computational Science, Hans Petter Langtangen
• Beginning Python Visualization: Crafting Visual Transformation Scripts, Shai Vaingast
• Dive Into Python, Mark Pilgrim
• Foundations of Agile Python Development, Jeff Younker
• Beginning Python: From Novice to Professional, Magnus Lie Hetland
http://site.ebrary.com/lib/ualberta/home.action
• Python Programming for the Absolute Beginner, Michael Dawson
• Gray Hat Python: Python Programming for Hackers and Reverse Engineers, Justin Seitz
• Python: Create - Modify – Reuse, James O. Knowlton
• Python Power!: The Comprehensive Guide, Matt Telles
Most recently published (and latest editions) listed from top to bottom
UofA e-books
(subscription is accessible through an on-campus computer with a UofA IP address or CCID login)
http://proquest.safaribooksonline.com/
• The Python Standard Library by Example, Doug Hellman
• Programming Python, Mark Lutz
• Python Algorithms: Mastering Basic Algorithms in the Python Language, Magnus Lie Hetland
• Head First Python, Paul Barry
• Python Testing, Daniel Arbuckle
• The Quick Python Book, Vern Ceder
• Python Programming for the Absolute Beginner, Michael Dawson
• Python Pocket Reference, Mark Lutz
• Learning Python, Mark Lutz
• Python Essential Reference, David M. Beazley
• Python: Visual QuickStart Guide, Toby Donaldson
• Expert Python Programming: Learn best practices to designing, coding, and distributing your
Python software, Tarek Ziadé
• Python Programming in Context, Bradley Miller and David Ranum
• Python Power!: The Comprehensive Guide, Matt Telles
• Python Phrasebook: Essential Code and Commands, Brad Dayley
• Core Python Programming, Wesley J. Chun
• Python in a Nutshell, Alex Martelli
• Python Cookbook, Alex Martelli, Anna Ravenscroft, and David Ascher
Do you feel like
So, are you now a you’ve found the
fledgling OR ‘holy grail’ of
pythoneer? programming
languages?