11 Introduction To Python
11 Introduction To Python
LESSON 11
Why Python?
Simple and easy to learn
Free, Open source
Cross Platform
Interpreted Language
Object oriented
Embraced by geospatial community, including
ESRI
When you write more complex scripts, it will be helpful to use an integrated
development environment (IDE), meaning a program specifically designed to
help you write and test Python code, ex. PythonWin IDE.
Python IDE
Python comes with a simple default editor called IDLE;
However, in this course youll use the PythonWin integrated
development environment (IDE) to help you write code.
PythonWin is free, has basic debugging capabilities, and is
included with ArcGIS
Download:
https://sourceforge.net/projects/pywin32/files/pywin32/Build%
20219/pywin32-219.win32-py2.7.exe/download
Variables in Python
Variable names are case sensitive. myVariable is a different variable than
MyVariable.
Variable names cannot contain spaces.
Example
>>> print x + 3
5
>>> myTeam = "Nittany Lions"
>>> print myTeam
Nittany Lions
>>> string1 = "We are "
>>> string2 = "Penn State!"
>>> print string1 + string2
We are Penn State!
>>> x = 5
>>> x = x - 2
>>> print x
3
Python Syntax
Python is case-sensitive both in variable names and reserved words
You end a Python statement by pressing Enter and literally beginning a new line.
If you have a long statement that you want to display on multiple lines for
readability, you need to use a line continuation character, which in Python is a
backslash (\). You can then continue typing on the line below and Python will
interpret the line sequence as one statement.
Demo
Task: Add field(s) to a shapefile
Method 3: ModelBuilder
Method 4: Python
Open the Python window in ArcMap by
clicking the Python button in the
Geoprocessing menu
Python basics
Python treats + as sum, which works as expected with integer (int) and
floating point (float) objects.
You cant sum an int and a string (str), but you can concatenate two strings.
ArcPy commands
Every tool accessible from the ArcToolbox and Search panes can be run from
ArcPy.
In the example above, the Add Field tool from the Data Management toolbox is run.
From
results
window
From
Model
Builder
4. Paste the code into PythonWin or the Python code window to see
how you would code the same operation you just ran in Desktop in
Python.