Python For Arcgis: Ahmad Aburizaiza
Python For Arcgis: Ahmad Aburizaiza
Part 1
Ahmad Aburizaiza
Data Services Group - GMU Libraries
Spring 2016
What is Programming?
2
What is Programming?
3
What is Programming?
4
What is Programming?
Examples of simple programs running ordered instructions:
1.
a. Add the two numbers 2 and 8
b. Multiply the addition result by 5
2.
a. Create a circle
b. Assign it the red color
c. Draw it on the computer screen
3.
a. Open a CSV file
b. Read x and y coordinates
c. Create points from the read coordinates
d. Draw the points on the map
5
Programming Languages
A programming language is a set of instructions and commands in
a specific syntax different from other programming languages.
6
Programming Languages
7
Programming Benefits for GIS
1. Higher salaries and demand for GIS developers (desktop/web/mobile) in the
GIS related market.
8
Programming Benefits for GIS
9
Programming Benefits for GIS
10
Programming Benefits for GIS
2. Programming automates daily workflows.
11
Programming Benefits for GIS
3. It extends an application’s capabilities and/or functionalities
12
About Python
● Python is a an OOP “Object Oriented Programming” language.
● It was founded by Guido Van Rossum.
13
Python for GIS professionals
● For a GIS professional, you can also use Python for desktop, web, and mobile
development.
● The following are some examples of Python packages and frameworks:
○ arcpy for ArcGIS
○ pyqgis for QGIS
○ geoDjango is a web framework
○ shapely library
○ pyshp library
○ PySAL library
● This course will cover only arcpy for arcGIS.
14
arcpy package
● You have to have ArcGIS installed because arcpy needs the ESRI license.
● Python and arcpy can run in IDLE, ArcMap, or ArcCatalog.
● When coding in ArcMap or ArcCatalog, you do not have to ask Python to
use arcpy. This is done for you automatically.
● In IDLE, you have to tell Python that you will use arcpy.
● Always use the IDLE installed with ArcGIS. It can be found in the ArcGIS
folder under the start menu. Sometimes, you will have multiple IDLE
installations on your machine. For instance, SPSS installs IDLE for
statistical coding.
15
Hello world! Program
● The Hello world! program is the most basic program in
any programming language.
● Basically what we are trying to do is to print the sentence
Hello World! on the screen.
● In Python, we use the command → print(...)
print('Hello world!')
16
Python in ArcMap
17
Python in IDLE
18
Variables
Assigning the value
X = False
Variable names Variable values
Average = 2.5
myUniv = "GMU"
19
Variables : Naming Validity
Variable Name Validity
averageGrade Correct
AverageGrade Correct
average_grade Correct
AVERAGE_GRADE Correct
Average-grade Wrong
2average_grade Wrong
averageGrade2 Correct
_averagegrade Correct
Average%grade Wrong
!average_grade Wrong
20
Variables : Naming Recommendations
● Have meaningful names
● Try to make the names shorter
● Use comments to describe your variables as well as all syntax
Variable Name Recommendation
averageGrade Recommended
TheAverageGradeOfStudents Not recommended
average_grade Recommended
A_G Not recommended
_a_grade Not recommended
AvErAGEGraDE Not recommended
21
Variables : Types
Numeric
● integer, a whole number with no decimal value → examples: 2, 0, -1, 679, -51
● float, a number with a decimal value → 2.0, 0.0, -1.0, 679.0, -51.0, 1.23, 0.001
Textual
● string, a sequence of alphanumeric and special characters. The string value can be wrapped in
double quotes or single quotes → examples, 'GMU', "GMU", 'GMU2', "GMU2", '#GMU',"#GMU"
Boolean
22
Variables : Numeric
x=9
y=3
z = 4.0
Operation Symbol Example
Addition + x + y => 12, y + z => 7.0
Subtraction - y - z => -1.0, x - y => 6
Multiplication * y * z => 12.0, y * x => 27
Division / y / x => 0.33, z / 0 => ERROR
Remainder % x % y => 0, z % x => 4.0
To the power ** z ** y => 64.0
23
Variables : Numeric
x=9
y=3
z = 4.0
Example Result
x*y+x 36
x+y*z 21.0
x+y*z+x 30.0
(x + y) * z + x 57.0
24
Variables : Boolean
x = True
y = False
Example Result
x and y False
y or y False
x or x True
x or y True
25
Variables : Boolean
x=1
y=2
z = 2.0
Example Result
x == y False
x>y False
y>x True
y >= x True
y == z True
26
Variables : Textual "String"
univName = 'GMU'
numberOne =1
collegeName = 'College of Science'
departName = 'GGS'
Example Result
28
Variables : Textual "String"
Method Description Example
str1 = 'Fall2009'
str2 = 'Fall 2009!'
isalnum() Returns True if all characters are alphanumeric
print(str1.isalnum()) => True
print(str2.isalnum()) => False
isalpha() Returns True if all characters are alphabetic print('Fall2009'.isalpha()) => False
isdigit() Returns True if String has digits only print('2009.21'.isdigit()) => False
Returns True if the string is in title format based print('George Mason'.istitle()) => True
istitle()
on case-format print('George MASON'.istitle()) => False
title() Returns the title format of a string print('gEorGe mAsoN').title()) => 'George Mason'
lstrip() Removes leading white spaces print(' a a '.lstrip()) => 'a a '
rstrip() Removes trailing white spaces print(' a a '.rstrip()) => ' a a'
strip() Performs both rstrip() and lstrip() print(' a a '.strip()) => 'a a'
29
Assigning Values to Variables as User Input
● Previously, we assigned the values to variables through code.
● Python gives us the option to assign the values using user input.
● x = input('Please enter a number')
● The code will display the 'Please enter a number' message on the
screen and wait for user’s input.
● The user’s input will be assigned to the variable x
30
Commenting the Code
● Commenting the code or documenting the code is very important.
● It explains the code to others or it reminds you about what you did in your old code.
● The # sign comments one line. To comment multiple lines use ''' and then close the
comment with '''
val1 = 17
val2 = 55
val3 = 101
# The following line prints the average of val1, val2, and val3
print((val1+val2+val3) / 3)
'''
Written by Ahmad Aburizaiza
For educational use
'''
31
Code practice
32
Indentation
● Indentation in Python is similar to using parenthesis {} in other programming languages.
● It is used to define blocks of code inside statements such as conditions, functions, loops, classes.
● For instance, the code in block 2 will not run unless the code in block 1 permits.
● The code in block 3 will run if block 1 permits and then block 2 permits.
33
Conditions
● Conditional statements are used to run an interior block based on the
condition of the statement.
● if statements are the most common conditional statements in
programming languages.
x=3
y=7
if x > y:
z = 'ABC'
34
Conditions
month = 10
day = 1
fiscalYear = True
if month == 6:
print("It is June")
if day <= 5:
print("It is the beginning of the month")
if fiscalYear:
print("it is a fiscal year")
35
Conditions
raining = True
cold = True
36
Conditions
randNum = input('Please enter a number: ')
if randNum % 2 == 0:
print( randNum + ' is divisible by 2')
elif randNum % 3 == 0:
print(randNum + ' is divisible by 3')
else:
print(randNum + ' is not divisible neither by 2 nor 3')
37
Lists
● A list is a sequence of data values stored as one variable.
● The data values in a list are called elements.
● Each element is assigned an index.
● In Python, you can create a list of different variable types. It is not
recommended but you can do it.
intList = [1, 7, 2, 5, 4, 6, 3]
stringList = ['a', 'b', 'abc123', '@TipsForGIS']
mixedList = [1, 'a', 2, '3', 'xy']
38
Lists
intList = [2, 7, 1, 5, 4, 6, 3]
stringList = ['a', 'b', 'abc123', '@TipsForGIS']
mixedList = [1, 'a', '22', 75, 'xy']
print(intList[0]) => 2
print(intList[1]) => 7
print(intList[-1]) => 3
del(mixedList[3]) => the element 75 will be deleted.
mixedList.append(101) => adds a new element with a value of 101
intList.sort() => intList will be [1,2,3,4,5,6,7]
print(len(stringList)) => 4
39
Loops
● A loop is control that forces repetition of interior code block(s).
● The for loop is a popular loop in programming.
● The while loop is another popular loop in programming.
● When writing loops, be careful not to write an infinite loop.
41
Conditional Statements Inside Loops
numList = [1,2,3,4,5,6,7,8,9]
for n in numList:
if n % 2 == 0:
print(str(n) + ' is even')
else:
print(str(n) + ' is odd')
print('Done')
42
Code practice
43
Functions
● A function is used to reuse certain code blocks.
● A parameter is a value that you can pass to the function to use it.
Def functionName(param1,....):
line code1
line code2
line code3
…….
addTwoIntegers(2,3)
addTwoIntegers(30,40)
Return-value function
def addTwoIntegers(int1,int2):
return int1 + int2
a = addTwoIntegers(2,3)
b = addTwoIntegers(30,40)
45
Why Functions?
side1 = 3 def pythagorean(side1,side2):
side2 = 4
largeSide = side1 * side1
largeSide = side1*side1 largeSide = largeSide + side2*side2
largeSide = largeSide + side2*side2 largeSide = largeSide ** 0.5
largeSide = largeSide ** 0.5 return largeSide
print(largeSide)
print(pythagorean(3,4))
print(pythagorean(1,1))
print(pythagorean(2,7))
46
The Scope
The scope of a variable or an object is where it can be accessed.
x=5
def func1():
x=7
print(x) => This x is the local x inside func1
func1()
print(x) => This x is the global x outside func1
47
Code practice
48
OOP : Classes and Objects
● OOP “Object Oriented Programming” is a concept of dealing with objects
in programming.
● We are not going to cover class creation. But we need to know how to use
predefined classes.
49
OOP : Classes and Objects
Class Car
Car objects
50
OOP : Classes and Objects
http://www.w3schools.com/js/js_objects.asp
51
Simple Class Definition
class Person:
def __init__(self,name,age,weight,height):
self.name = name
self.age = age
self.weight = weight
self.height = height
def walk(self):
print(self.name + ‘ is walking’)
def eat(self):
print(self.name + ‘ is eating’)
52
OOP
● A module is .py file contains a collection of classes independent functions and/or variable.
● The __init__.py makes the folder a Python package. It can be left empty.
Package
53
OOP
Function1
Function2
Variable1 Variable2
Variable3 Variable4
Module
54
OOP
To import a class from a module, type in:
from moduleName import ClassName
OR
from moduleName import*
OR
import moduleName
MapDocument
mapping
arcpy
56
Importing a Class from arcpy
To import the MapDocument class:
→ import arcpy.mapping.MapDocument
title save()
author saveACopy(fileName)
MapDocument
activeDataFrame makeThumbnail()
credits deleteThumbnail()
57
Conclusion
Topics not covered in the workshop: break and continue in loops, read/write
files, and class creation