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

Python For Everyone ArcMap

This document provides an introduction to automating workflows using Python scripts in ArcGIS. It discusses choosing a scripting environment, what makes a Python script, and common data types like literals, variables, lists, tuples, and dictionaries that are used as the "ingredients" in scripts. Functions and statements are described as the "instructions" in scripts. Examples are given of different data types, functions, and statements to illustrate how they are used as the building blocks for creating Python scripts. The overall summary is that this document serves as an introduction to the basic concepts and components needed to start writing Python scripts.

Uploaded by

Fadamoro John
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

Python For Everyone ArcMap

This document provides an introduction to automating workflows using Python scripts in ArcGIS. It discusses choosing a scripting environment, what makes a Python script, and common data types like literals, variables, lists, tuples, and dictionaries that are used as the "ingredients" in scripts. Functions and statements are described as the "instructions" in scripts. Examples are given of different data types, functions, and statements to illustrate how they are used as the building blocks for creating Python scripts. The overall summary is that this document serves as an introduction to the basic concepts and components needed to start writing Python scripts.

Uploaded by

Fadamoro John
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

INTRODUCTION

Do you spend a lot of time repeating workflows, such as copying data, editing files, and setting
up map documents? Did you know that you can use Python to automate data reproduction, data
management, map document display, and many of your other daily tasks in ArcGIS?

This course provides the building blocks needed to use Python. You will create and run scripts
using these building blocks, and you can apply them directly inside of ArcGIS and to your own
workflows.

Video Where to start

Choosing scripting environments


There is not a specific environment you must use when creating and running a Python script—
you can choose the scripting environment that you prefer. However, depending on the task in
your script, one environment may be a better choice than the other. The following questions will
help you determine which environment will work best for your script's task—ArcMap Python
window or an IDE, such as PythonWin.
What makes a Python script?
When you run a Python script, what is actually running?

A Python script is a sequence of instructions. The structure and arrangement of the instructions
are referred to as syntax. Python uses a variety of language elements to create these instructions,
including data types, statements, and functions.

If you think of a Python script as a recipe, the data types are the recipe's ingredients, and the
statements and functions are the recipe's instructions. You need ingredients and instructions for a
recipe, just as you need data types and statements/functions for a script.

EXERCISE 1

RUN PYTHON SCRIPTS

Click here to access the exercise

Creating scripts
After you decide where to run a script, the next step is to set up the script and determine the
ingredients and instructions you will need.

This demonstration provides an overview of one way to set up a script and its ingredients.

Video creating scripts


Data types
Data types are created, deleted, changed, and manipulated to complete the script's task. Each of
the various data types can be referred to as an object. Deciding which data type to use depends
on what you want to do with it. Data types, like ingredients, can be used in instructions to create
your recipe or script. Here are a few common data types:

 Literal
 Variable
 List
 Tuple
 Dictionary

Literal

A literal is the actual value you are working with. It can be a number or text (string). In the
example, the literals are the green values inside the table.

Python uses quotation marks to differentiate between number and string literals. Notice that Italy
is the only string value, so it is enclosed in quotation marks.

Because the literal 1 is the value of ID, it might be better suited as a string because it does not
need number functionality, such as addition or multiplication. To represent a number as a string,
enclose it in quotation marks: "1".

Strings are a collection of one or more characters. Each of these characters has an index that can
be used to return the character. The index starts with 0 and increases from left to right.

The following is an example of a list index used to return the third character in the Italy string:

>>> Country = "Italy"
>>> Country[2]
'a'
Variable

A variable is a value used to represent the literal. It is similar to shorthand in the sense that you
are creating a name to represent the literal value.

Because variables store the information of the literal, you can use the variable in the instructions
of your script. In the example, Country is the variable for Italy. If a script instruction requested
the value of Country, Python would return Italy.

>>> Country = "Italy"
>>> Country
'Italy'

Assigning variables is useful when editing a script to use a new value. Instead of replacing the
value throughout the script, you only need to replace the value assigned to the variable. In the
following example, you could reassign the variable Country with a different value, and it would
automatically change the concatenation using that new value.

>>> Country = "Italy"
>>> "The country is named" + Country
'The country is named Italy'
List

A list stores a sequence of items inside brackets and separates the items using commas.

In the example, the variable AttributeList represents a list of the attribute literals (1, "Italy",
12000, 40000000). Because literals and variables are interchangeable, AttributeList can also
represent a list of the attribute variables (ID, Country, Pop, Area).

Lists help you automate a task through a series of items. You can execute the task on each item,
or you can call specific items using the item's index. A list, like a string, is a collection, but a list
is a collection of one or more items. Each item has an index that starts with 0 and increases from
left to right.

The following is an example of a list index used to return the fourth item in the AttributeList:

>>> AttributeList = [1, "Italy", 12000, 40000000]
>>> AttributeList[3]
40000000
Tuple

A tuple stores a sequence of items, like a list; however, the tuple is immutable, meaning you
cannot change it. A tuple is useful to ensure the integrity of a sequence throughout a script.

The sequence closures enable Python to distinguish between a tuple and a list. A list uses
brackets to enclose the sequence of values, while a tuple uses parentheses.

Similar to a list, a tuple is indexed and these indexes can be used to reference an item from the
sequence.

>>> AttributeTuple = (1, "Italy", 12000, 40000000)
>>> AttributeTuple[3]
40000000
Dictionary

A dictionary stores pairs (called items) using a key and associated values. You can get a value by
looking up the key. Think of a dictionary like an address book: you can look up someone's name
(key) and get their associated information (value). Dictionaries are similar to list indexes, except
you can retrieve an item using a key, instead of an index.
In the following example, when you look up Area (key), you get 40000000 (its value).

>>> AttributeDic= {"ID": 1, "Country": "Italy", "Pop": 12000, "Area": 40000000
}
>>> AttributeDic["Area"]
40000000

EXERCISE 2

CREATE DATA TYPES

Click the link to access the exercise

Working with functions and statements


Data types, like ingredients, can be used in instructions in order to create your recipe, or script.
There are many types of instructions to use in a script. This demonstration provides a few
examples of statements and functions that can be used for a script's instructions.

In this demonstration, a database manager has a folder of text files that list the contents of each
database. Because shapefiles do not sit inside the database, the manager needs to remove all
shapefiles from these lists and has asked for a Python script to automate this task.

Video working with functions and statements

Function syntax

A function's syntax begins with the name of the function and is followed by its parameters,
enclosed in parentheses. In the same example, pow is the function; the number to convert (Area
value) and conversion power (2) are its parameters. The returned value is the value of 40000000
raised to the second power (1600000000000000). The L at the end of the value indicates that it is
a long integer.

Built-in functions

Python provides many built-in functions that are ready to be used when you start writing a script.
A few commonly used built-in functions are shown here; for a complete list, see the Python
documentation.

len(object) – returns the length of the object

>>> attributeList = [ID, Country, Pop, Area]
>>> len(attributeList)
4

open(name, mode) – opens a file in read, write, or append mode

>>> open("C:\Users\Desktop\attrInfo.txt", "r")
<open file ' C:\Users\Desktop\coords.txt ', mode 'r' at 0x17F042E1>

max(object) – returns the largest value in a tuple or list

>>> areaTuple = (40000000, 23908, 1200000000)
>>> max(areaTuple)
1200000000
Methods

Functions that are associated with a specific data type or object are referred to as methods. Like
other functions, methods perform an action, but the action depends on the data type it is
associated with. For example, a string method like capitalize will capitalize the string value it is
associated with (attached to).

String method: capitalize

>>> Country = 'italy'  
>>> Country.capitalize()
'Italy'

Notice that the method capitalizes the string value (italy) not the variable (Country).

A string method like capitalize does not work on other data types, such as a list. A list is not a
string, it is a sequence. A list has different methods that complete tasks for sequences. For
example, you can count the number of times that a string or a number occurs within a list.

List method: count

>>> CountryList = ["Italy", "Germany", "China", "Germany"]
>>> CountryList.count("Germany")
2

A method's syntax differs from other functions because it begins with the method's associated
data type. For example, the count method begins with the intended list, CountryList. The data
type is followed by a period, the method name, and then the method's parameters.
Additional functions

More functions are available by importing modules. Think of a module as a container of


functions that have the same theme. For example, the math module has functions that complete
math-related actions. Modules are not loaded into Python upon startup, but importing a module
(using the import statement) loads it to memory and makes the functions available in Python.

You can use the help built-in function to find a list of available modules.

>>> help ("modules")

Statements
To perform an action in a script that does not return a value (for example, importing a module),
you will use statements in your script instructions.

Some statements, like the print statement, are used like a command. The print statement writes
the textual (or string) representation of a data type or function value. The print statement is often
used in a script to print the string representation to the Python Console.
Other statements can extend script functionality by automating tasks and incorporating
conditional statements into the script. For example, the following script uses a conditional if-else
statement to determine if the amount is less than, greater than, or equal to 50.

In Python

amount = 49
if amount >= 50:
     print ("Amount is greater than or equal to 50")
else: 
     print ("Amount is less than 50")

Unlike functions, statements can perform several operations or, as in this case, contain several
functions.

Automating a task using statements

Looping statements allow you to automate the same task for several items. For example, the
following Python script uses a for-in statement to replace feet with meters for each of the area
items in the AreaList.

In Python

Country = "france"
if Country == "italy": 
     print ("This country is Italy")

elif Country == "france":
     print ("This country is France.")

else:
  print ("This country cannot be verified")
Other statements that can you use

This list of commonly used statements includes previously mentioned statements, along with a
few other examples.
EXERCISE 3

CREATE A SCRIPT

Click the link to access the exercise

Python in ArcGIS
You can use your Python script, function, or statement directly inside ArcGIS to change labels,
automate analyses, and more.

The following demonstration uses some of Python's ArcGIS functionality to set up a map that a
fictional organization (Protect Birds, Inc.) will use to analyze nesting site proximity to roads.

Video Python in ArcGIS

Site packages
Python functionality in ArcGIS can range from a simple label expression using one of Python's
built-in functions to a complex geoprocessing script. Geoprocessing functions, along with other
GIS-related functions, are made available through the ArcPy site package.

Think of a site package as a container of modules and functions. The modules are a container of
functions based on a theme, such as the mapping module or the spatial analyst module. The
ArcPy site package is a container of GIS-related functions and modules.
The ArcPy site package is preloaded into ArcMap and, therefore, readily available. However,
outside ArcMap, the site package acts as a module, which needs to be imported to make its
functionality available.

The syntax used to call a function from the site package starts with the site package, is followed
by the module (if there is one), and ends with the function.
EXERCISE 4

USE PYTHON IN ARCGIS

Click the link to access the exercise

Handling errors
As you develop and run scripts, you will find that they are not always perfect. You may
encounter one, or several, errors. This demonstration identifies different types of scripting errors
and provides tips for resolving them.

Video handling errors

Types of errors
If Python encounters an error with your script, the first step in handling the error is to determine
which type of error has occurred. Two types of errors that may occur when running your scripts
are syntax errors and exceptions.

Syntax errors

Syntax refers to the rules used to create the ingredients and instructions of your script. Therefore,
a syntax error applies to a structural error in which a rule was broken or not enforced.

Exceptions

After you have corrected all the syntax errors, your script can still fail and generate an error.
These errors are referred to as exceptions and are usually caused by errors during the execution
of your script.

Exceptions are typically raised because of an error in the logic or decision-making steps of your
script. An exception can also occur if your script tries to work with data that it is not expecting.
Basic debugging tips
After you determine the type of error your script encountered, the next step is to debug. Using a
debugging decision tree can help you debug your script.
Debugging decision tree

Common errors

Review your script, looking for some of the common syntax errors:
Pseudocode
Review your pseudocode to determine if any steps are missing in your workflow:

#Assign variables
strm = r"C:/Data/Strms.shp"
buff = r"C:/Data/StrmsBuff.shp"

#Create 1000ft buffer 
arcpy.Buffer_analysis(strm, buff, "1000 feet")

If you tried to execute this script in PyCharm, you would receive an exception. By reviewing the
workflow, you can see that the script is trying to use a function from ArcPy without importing
the site package. If you imported ArcPy before running the function, the script would execute
successfully.

Comment code
Comment blocks of code, which Python will not execute, to further narrow down the location of
the error.

#Assign variables
strm = r"C:/Data/Strms.shp"
buff = r"C:/Data/StrmsBuff.shp"

#Create 1000m buffer 
#arcpy.Buffer_analysis(strm, buff, #1000 + "meters")

If the script successfully executes after commenting a block of code, then you can determine that
the error is with that block (in this case, the Buffer function).

Print statements
Add print statements to indicate when steps in the script are processing or variables have been
assigned. You can see which steps have executed before the script fails.

#Assign variables
strm = r"C:/Data/Strms.shp"
path = r"C:/Data/StrmsBuff"
buffList = ["100", 500, "700"]

#Create 100, 500, 700 ft buffers 
for buff in buffList:     
     print (buff + " processing")
     arcpy.Buffer_analysis(strm, path + buff + ".shp", buff + "feet")
The print statement identifies which item in buffList is processing. If the second item, 500, is
processing when the script fails, then the error has been narrowed down to that list item.

EXERCISE 5

SOLVING SCRIPTING ERRORS

Click the link to access the exercise

You might also like