0% found this document useful (0 votes)
20 views

Intro To Python

This document introduces Python programming concepts for geoprocessing including basic code components, writing and running code, variables, data types, modules, functions, and objects. It also covers running a simple buffer analysis script as an example.

Uploaded by

Yousef Al-Ashqar
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Intro To Python

This document introduces Python programming concepts for geoprocessing including basic code components, writing and running code, variables, data types, modules, functions, and objects. It also covers running a simple buffer analysis script as an example.

Uploaded by

Yousef Al-Ashqar
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Beginning Python

• geoprocessing
• why this course uses Python
• where to write code
• input to scripts
• basic Python code components

Dr. Tateosian
In-class exercise

“Simple buffer” goals:


• Get immediate feedback from Python
• Run a Python geoprocessing statement
• Understand the connection between Python code and ArcGIS tools.

arcpy.env.workspace = 'C:/gispy/data/ch01/‘

arcpy.Buffer_analysis('park.shp',
'C:/gispy/scratch/parkBuffer.shp', '0.25 miles',
'OUTSIDE_ONLY', 'ROUND', 'ALL') 2
ESRI Geoprocessing

Multiple ways to conduct geoprocessing in ArcGIS


Python

Export
models to
scripts

Call scripts
from models

Image modified from Prof. Piotr Jankowski at http://geography.sdsu.edu/People/Pages/jankowski/public_html/web683/lectures683.htm 3


Why Use Python?
•Good ‘starter language’ JavaScript Python

•Automate tasks.

•Batch processing.

•Schedule processes.

•Intuitive syntax.

•Installed with ArcGIS 10.x and examples are given.

•Coverity report:
• http://wpcme.coverity.com/wp-content/uploads/2013-Coverity-Scan-Spotlight-Python.pdf

4
Where to write code?

• Any text editor or the ArcGIS Python Window;


However, IDE’s have more.
• Integrated development environment (IDE)
• Interactive.
• Write/save/run scripts.
• Color coding
• Tab completion
• Syntax checking
• Debugging
• Python IDEs:
PythonWin & PyScripter (for Windows OS)
Wingware (for Linux/Mac OS)
iPythonNotebook (online IDE)

5
PythonWin Interface
Menus
Toolbars
debugging, standard

Script window
Write and save code
(permanent)

Interactive window
Test lines of code
Report messages
(temporary)

Feedback 6
Syntax error or success
PythonWin standard toolbar
Standard toolbar

7
‘add.py’ example, line by line

# add.py adds two input numbers.


import sys

a = int(sys.argv[1])
b = int(sys.argv[2])
c = a + b
print “The sum is”, c

Concepts:
• # means what follows on that line is a comment just for human readers
• import sys (lets you use things from the sys module)
• variables (a and b are variables; they are assigned values with “=“ )
• sys.argv (argument vector; the list of things you send in when you run it)
• int (converts a string to an integer)
• print

8
In-class: Run add.py in PythonWin
• Open the program add.py
• Run the program or Ctrl+R

• Pass arguments (with space between arguments)


Output:
The sum is 11

Output:
The sum is 11
sys.argv[1] + sys.argv[2] = 56 WHY?
• Uncomment the bottom sys.argv[0] = C:\<my directory path>\add.py
Select and click (Alt + 4) sys.argv[1] = 5
Run again. sys.argv[2] = 6 9
What do you see?

10
Python components • Variables

• Comments

• Keywords

• Modules

• Indentation

• Objects

• Functions

• Built-ins

• Assignment
statements

• Data structures
Syntax highlighting:
text color/font based on code features 11
Basic building blocks

• Variable is a name that represents a value:


• Is bound to a value.
• Value is not stored in variable; Variable just refers
to (points to) a value stored somewhere in
memory.
• Expression is a value (number or string)
Examples: 2+2
‘My string’
• Statement is an instruction (does something or
changes something)
Examples: print “Hello world”
FID = 145
• Assignment statement sets the value of a
variable.

12
Commenting code
# conditional_addfield.py
Header
# Purpose: Add a field, if it does not already exist.
(documentation
# Usage: field_name
comments)
# Example input: “bridges”
# Output: A shapefile with the new field added, if it didn’t already exist.
# Author: Donald Duck 8/22/2065
# Modified: Silvester 3/06/2080 to run in PythonWin

# GET input field name


# SET field name to input field name Body
# IF field exists THEN (explanatory
#Reset values to zero comments)
# ELSE
# CALL add field
# ENDIF

13
Python Keywords

• have special meaning in Python

• may not be used as variable names:


>>> exec = “python.exe"
Traceback ( File "<interactive input>", line 1
exec = “python.exe"
^
SyntaxError: invalid syntax

• case sensitive, so use if not IF or If


14
Standard modules
• A Python module is a set of related code.
• Python has a set of standard modules automatically installed.
Examples: math, os, sys, shutils, winsound, time
• Import a module to use the functions & variables (properties) it contains.
• Import statements use keyword import followed by 1 or more module name.
• import sys, os, arcpy
• After import, use dot notation to utilize module functions and properties.
• moduleName.functionName(argument1, argument2, …)

• Examples:
• ‘radians’ is a ‘math’ module function:

• ‘argv’ is a ‘sys’ module property:

• ‘listdir’ is an ‘os’ module function:

15
Variable naming rules & conventions
• Variables are case sensitive
freeways = “Freeways.shp”
Freeways = 20000

• Avoid special characters in names ( / \ & % # ! , . ; : and so forth)


• Names can not start with numbers
• Case conventions
•First word lower case, capitalize each successive word
(Lower camel case)

• tableFieldName = “Street”

•Acronym at the beginning, use lower case letters


•gdbPath = “C:\\testerData.mdb”

•Acronym in the middle or at the end, use upper case letters


•inputFC = “streets.shp”

• When practical, use descriptive variable names


• sa = s * s hypothenuse = math.sqrt(adjacent**2 + opposite**2)
• squareArea = side * side r = math.sqrt(dx**2 + dy**2)
16
Indentation
Block of code: related code inside of a control structure
Examples: FOR block, IF block, WHILE block
Code inside a block is indented to the same level

View > whitespace

17
Python Objects
• Everything in Python is an Object
• Each object has:
• A value data item represented by
an object
• An Identity unique identifier, similar
to a memory address
>>> river = "Arno“ • A Type specifies what kind of values
>>> river an object can hold and which
'Arno‘ operations are allowed
>>> id(river)
15446688
>>> type(river)
<type 'str'>
>>> river = 96 Dynamically typed variables
>>> type(river)
<type ‘int’>
18
Python built-in Functions

Don’t use built-ins


as variable names!

19
Functions
>>> round(1.7) >>> min(1, 2, 3)
2.0 1

• function – a named set of code that performs a task


Examples: round, min, help, int, print…

• built-in function – a function supplied by Python


Examples: type, id, round, min, help, int, print…

• function call -- a code statement that invokes a function


•For example, we called the round function, then we called the min function.

• Passing arguments -- providing input for a function


•Example: 1.7 is passed into the round function

• Return value – information returned from a function


e.g., the round function returned a 2; the min function returned a 1.
But the help function doesn’t return anything. It just prints something.
20
The help function

• shows how the function can be used


• prints a template (a signature)
• the arrow points to what it gives you as a return value
>>> help(round)
Help on built-in function round in module __builtin__:
round(...)
round(number[, ndigits]) -> floating point number

>>> help(min)
Help on built-in function min in module __builtin__:
min(...)
min(iterable[, key=func]) -> value
min(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its smallest item.
With two or more arguments, return the smallest
argument.
Parameter vs. argument
• the built-in help function prints a template (a signature).
• the signature lists the parameters
• parameter – piece of info. passed in to a function
>>> help(round)
Help on built-in function round in module __builtin__:
round(...)
round(number[, ndigits]) -> floating point number

returned by the function


signature parameters

• argument -- the expression being passed into the function


• >>> round(1.7) >>> min(1, 2, 3)

argument arguments 22
Built-in constants
• Values assigned as soon as Python is launched
• Examples: True, False, None

>>> type(True)
<type 'bool'>

>>> True
True
•Geoprocessing example:
>>> import arcpy
>>> arcpy.env.overwriteOutput = True

23
Built-ins exceptions
• Exceptions: common errors that Python can identify automatically.

• An exception is thrown when one of these errors is detected.

• A traceback message is generated and printed in the Interactive Window

• The ‘bad’ script will stop running when an exception is printed.

• Examples: SyntaxError, TypeError, NameError

24
In class: tryMe

• learn how to execute single lines of Python code


interactively
• call functions
• throw exceptions
• type each code statement one at a time in the
interactive window
• before running each statement, predict the results
• select the return (or enter) to run each line of code
• how accurate were your predictions?

25
‘tryMe’ take home lessons

1. Variable names are case-sensitive.


2. Python dynamically changes the data type when you assign
values to a variable.
3. Don’t use keywords or built-ins as variable names!

>>> type(min)
<type 'builtin_function_or_method'>
>>> min(1, 2, 3)
1
>>> min = 5
>>> min(1, 2, 3)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
>>> type(min)
<type 'int'>

26
Summing up

• Topics discussed
• Why use Python
• Integrated development environments (IDEs)
• Passing arguments into scripts
• Basic Python code components: naming & initializing variables,
comments, keywords, modules, indentation, objects, functions, built-ins
functions, constants, exceptions, assignment statements, data structures
• Up next
• Data structures: integers, floats, strings, lists, tuples…

• Additional topics (see Appendix)


• how to install PythonWin
• exporting scripts from Modelbuilder

27
Appendix

28
Extra exercise – Exporting a module
• ModelBuilder models can be exported to Python scripts.
• Right click on Model >
Model menu > Export > To Python Script…

• Run the script in PythonWin


with 700 ft

Arguments: “700 feet”

• Look at the feedback bar!

• Check for the buffer output 29


Export from original model
exported1.py

Line 23 sets the output name to be


the same as the input name!

30
Export from modified model
exported2.py

It runs successfully once, but throws an expection the second time!

Once the output has been created, it won’t overwrite it, unless told to do so as follows:

arcpy.overwriteOutput = True

‘Exporting a model’ exercise take home message: Yes, you can export them,31

You might also like