Python
Python
Python
Introduction to Python
Python is a high-level programming language
Open source and community driven
“Batteries Included”
a standard distribution includes many modules
Dynamic typed
Source can be compiled or run just-in-time
Similar to perl, tcl, ruby
2
Why Python?
Unlike AML and Avenue, there is a considerable base
of developers already using the language
“Tried and true” language that has been in
development since 1991
Can interface with the Component Object Model
(COM) used by Windows
Can interface with Open Source GIS toolsets
3
Why not Visual Basic?
Visual Basic is still the method of configuring and
customizing ArcMap
If you have a button on the toolbar, it’s VB
Python scripts can be placed in ArcToolbox
Python can be run from the command line without
ArcMap or ArcCatalog being open
Using just the GIS Engine, lower overhead
Rapid prototyping, ease of authoring, etc.
4
Python Interfaces
IDLE – a cross-platform Python development
environment
PythonWin – a Windows only interface to Python
Python Shell – running 'python' from the Command
Line opens this interactive shell
For the exercises, we'll use IDLE, but you can try them
all and pick a favorite
5
IDLE – Development Environment
IDLE helps you program
in Python by:
color-coding your
program code
debugging
auto-indent
interactive shell
6
Example
Hello World
Python
print “hello world”
Prints hello world to
standard out
Open IDLE and try it out
yourself
Follow along using IDLE
7
More than just printing
Python is an object oriented language
Practically everything can be treated as an object
“hello world” is a string
Strings, as objects, have methods that return the result
of a function on the string
8
String Methods
Assign a string to a
variable
In this case “hw”
hw.title()
hw.upper()
hw.isdigit()
hw.islower()
9
String Methods
The string held in your variable remains the same
The method returns an altered string
Changing the variable requires reassignment
hw = hw.upper()
hw now equals “HELLO WORLD”
10
Other Python Objects
Lists (mutable sets of strings)
var = [] # create list
var = [‘one’, 2, ‘three’, ‘banana’]
Tuples (immutable sets)
var = (‘one’, 2, ‘three’, ‘banana’)
Dictionaries (associative arrays or ‘hashes’)
var = {} # create dictionary
var = {‘lat’: 40.20547, ‘lon’: -74.76322}
var[‘lat’] = 40.2054
Each has its own set of methods
11
Lists
Think of a list as a stack of cards, on which your
information is written
The information stays in the order you place it in until
you modify that order
Methods return a string or subset of the list or modify
the list to add or remove components
Written as var[index], index refers to order within set
(think card number, starting at 0)
You can step through lists as part of a loop
12
List Methods
Adding to the List
var[n] = object
replaces n with object
var.append(object)
adds object to the end of the list
13
Lists in ArcToolbox
You will create lists:
Layers as inputs
Attributes to match
Arrays of objects
You will work with lists:
List of field names
List of selected features
14
Tuples
Like a list, tuples are iterable arrays of objects
Tuples are immutable –
once created, unchangeable
To add or remove items, you must redeclare
Example uses of tuples
County Names
Land Use Codes
Ordered set of functions
15
Dictionaries
Dictionaries are sets of key & value pairs
Allows you to identify values by a descriptive name
instead of order in a list
Keys are unordered unless explicitly sorted
Keys are unique:
var[‘item’] = “apple”
var[‘item’] = “banana”
print var[‘item’] prints just banana
16
Indentation and Blocks
Python uses whitespace and indents to denote blocks
of code
Lines of code that begin a block end in a colon:
Lines within the code block are indented at the same
level
To end a code block, remove the indentation
You'll want blocks of code that run only when certain
conditions are met
17
Conditional
if and else
Branching
if variable == condition:
#do something based on v == c
else:
#do something based on v != c
elif allows for additional branching
if condition:
elif another condition:
…
else: #none of the above
18
Looping with For
For allows you to loop over a block of code a set
number of times
For is great for manipulating lists:
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
Results:
cat 3
window 6
defenestrate 12
19
Looping with For
We could use a for loop to perform geoprocessing tasks
on each layer in a list
We could get a list of features in a feature class and
loop over each, checking attributes
Anything in a sequence or list can be used in a For loop
Just be sure not to modify the list while looping
20
Modules
Modules are additional pieces of code that further
extend Python’s functionality
A module typically has a specific function
additional math functions, databases, network…
Python comes with many useful modules
arcgisscripting is the module we will use to load
ArcGIS toolbox functions into Python
21
Modules
Modules are accessed using import
import sys, os # imports two modules
Modules can have subsets of functions
os.path is a subset within os
Modules are then addressed by
modulename.function()
sys.argv # list of arguments
filename = os.path.splitext("points.txt")
filename[1] # equals ".txt"
22
Files
Files are manipulated by creating a file object
f = open("points.txt", "r")
The file object then has new methods
print f.readline() # prints line from file
Files can be accessed to read or write
f = open("output.txt", "w")
f.write("Important Output!")
Files are iterable objects, like lists
23
Error Capture
Check for type assignment errors, items not in a list,
etc.
Try & Except
try:
a block of code that might have an error
except:
code to execute if an error occurs in "try"
Allows for graceful failure
– important in ArcGIS
24
Let us dig a little further
25
What Is a Program?
Usually, one or more algorithms written in a
programming language that can be translated to run
on a real machine
Algorithm
Program
A real computer
The Program Development Process
(Data Flow)
Algorithm
Editor
Program in programming language
Compiler
A real computer
Input Output
The Program Development Process
(Control Flow)
Edit
Syntax errors
Compile
Run
Input Output
Runtime errors
Three kinds of errors
Syntax error : Some statement in the program is not a
legal statement in the language.
http://code.google.com/p/mediacomp-jes/ .
Input
Computation
Output
The Big Plan
We want to get some experience of programming simple
algorithms in a real programming language. This gives us an
understanding of how software is written and allows us to
test our algorithms to see if they work.
In Python, identifiers
Are made of letters, digits and underscores
Must begin with a letter or an underscore
Examples: temperature, myPayrate, score2
Keywords
Keywords are reserved words that have special
meaning in the Python language. Because they are
reserved, they can not be used as identifiers. Examples
of keywords are if, while, class, import.
Variables in Python
A variable has
A name – identifier
float
This type is for numbers with possible fraction
parts. Examples: 23.0, -14.561
Integer operators
The operations for integers are:
+ for addition
- for subtraction
* for multiplication
/ for integer division: The result of 14/5 is 2
% for remainder: The result of 14 % 5 is 4
Integer Constants
Integer Variables
Integer Operators
Parentheses
Python Assignment Statements
In Python, = is called the assignment operator and
an assignment statement has the form
<variable> = <expression>
Here
<variable> would be replaced by an actual variable
<expression> would be replaced by an expression
Python: age = 19
Python Assignment Statement
Syntax: <variable> = <expression>
Note that variable is on left
Semantics:
Compute value of expression
Store this as new value of the variable
10 40 400
Payrate Hours Pay
Assignment Example
Before
X Y Z
3 5 12
Execute
Z=X*3+Z/Y
After
X Y Z
3 5 11
Python Session
Python Session
What about floats?
When computing with floats, / will indicate regular
division with fractional results.
<variable> = input(<prompt>)
Here
<prompt> would be replaced by a prompt for the user
inside quotation marks
If there is no prompt, the parentheses are still needed
Semantics
The prompt will be displayed
User enters number
Value entered is stored as the value of the variable
Print Statement
For output we use statements of the form
print <expression>
Semantics
Value of expression is computed
This value is displayed