Python Variables

Python Basics I
GIS Applications
Spring 2017
1
Python and ArcGIS
Python is tightly integrated into ArcGIS Desktop
Python scripting allows you to create and automate new GIS
operations or automate a workflow (e. g. create a map, perform
some redundant tasks, perform a complete analysis).
import arcpy
roads = "c:/base/data.gdb/roads"
output = "c:/base/data.gdb/roads_Buffer“
# Run Buffer using the variables set above and pass the remaining
# parameters in as strings
arcpy.Buffer_analysis(roads, output, "distance", "FULL", "ROUND", "NONE")
2
Python Background
Python is an interpreted language – executes instructions directly
without compiling into machine language
Considered a scripting language - intended to be quick to learn
and easy to use. Good for quick prototyping
Python is a high level language – it has built in high-level data
types, such as arrays and dictionaries, and classes.
Has dynamic typing: majority of type checking is performed at
run-time as opposed to at compile-time.
In dynamic typing, values have types, variables do not.
3
Running Python - the Interpreter
An integrated development environment for Python named IDLE
installs with ArcGIS desktop
The Integrated DeveLopment
Environment (IDLE) provides a
default editor, search capabilities
and a symbolic debugger.
Once Python starts running in interpreter mode, using IDLE or a
command shell, it produces a prompt, which waits for your input.
4
Python Variables
A variable is a name that refers to a value.
When you create a variable you reserve some space in
memory for a value.
Based on the data type of the value, the interpreter allocates
memory and decides what can be stored in the reserved
memory.
a=4
5
Python Variables
Variables are created when a value is assigned to them
The equal sign ('=') is used to assign a value to a variable
>>> x = 4
Variables must be “defined” (assigned a value) before they can be
used, or an error will occur
>>> a
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
a
NameError: name 'a' is not defined
6
Python Variables
Variables do not need to be declared explicitly
Their datatypes are inferred from the assignment statement.
Python supports the following data types:
•Boolean
•integer
•long
•float
•string
•list
left = True
x = 10
y= 123456789435617L
z= 13.33
name = “George”
mylist=["one", 2, 3.0]
7
Python - Adding comments
A hash sign (#) that is not inside a string literal begins a
comment.
All characters after the # and up to the end of the physical line
are part of the comment and the Python interpreter ignores
them.
8
Python Variables
>>> count = 1
>>> mileage = 12345.12
>>> name ='kate'
#an integer assignment
# a float assignment
# a string assignment
Use single or double quotation marks to indicate that you are
declaring a string variable
>>> print name, count, mileage
kate 1 12345.12
Use a print statement to write the results of operations.
A value can be assigned to several variables simultaneously:
>>>>a=b=c=d=1
>>> print a,b,c,d
1111
9
Python Variables
You can assign a number as a string variable by putting it in quotes.
>>> mynumber ="4"
Then it will behave like a string, not a number.
>>> count+mynumber
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
count+mynumber
TypeError: unsupported operand type(s) for +: 'int' and 'str'
10
Variable naming
Variables in Python follow the standard of an alphanumeric
name but must begin with a letter or underscore.
Variable names cannot begin with a number.
Variable names cannot contain spaces.
Variable names are case sensitive.
mynumber is a different variable than Mynumber or MyNumber
>>>>Mynumber
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
Mynumber
NameError: name 'Mynumber' is not defined
11
Variable Naming
A recommended practice for Python variables is to name the
variable beginning with a lower-case letter, then begin each
subsequent word with a capital letter
myName, myLastName, roadsTable, bufferField1.
Make variable names meaningful so that others can more easily
read your code – and it will also help you read your code.
12
Python Reserved Words
Variables cannot be any of the special Python reserved words.
Python keywords contain lowercase letters only.
and
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield
13
Python statements
A statement is an instruction that the Python interpreter can
execute.
A simple statement consists of a single logical line
a=1 # an assignment statement
b=2
print a # a print statement
print b
Assignment statements are usually the most common type
Assignment statements bind variable names to values
An assignment statement produces no output.
A print statement produces an output
14
Python - Evaluating expressions
An expression is a combination of values, variables, and
operators.
Operators and operands
Operators are special symbols that represent computations like
addition and multiplication. The values the operator uses are
called operands.
The symbols +, -, and /, and the use of parenthesis for grouping,
mean in Python what they mean in mathematics.
The asterisk (*) is the symbol for multiplication, and ** is the
symbol for exponentiation.
15
Python - Evaluating expressions
When you type an expression on the command line, the
interpreter evaluates it and displays the result:
>>> 1 + 1
2
Not every expression contains all of these elements.
A value all by itself is considered an expression, and so is a
variable
>>> 324
The left-hand side of an assignment statement has to be a
variable name, not an expression
>>> a + 1 = b
16
Number Variables
Number data types store numeric values.
Python supports four numerical types:
int (signed integers) -have at least 32 bits of precision
long (long integers - have unlimited precision)
float (floating point real values)
complex (complex numbers)
a = 5
b = 1123456789324576829L
c = 13.33
>>> type(a)
<type 'int'>
>>> type(b)
<type 'long'>
17
Number Operations
The Python interpreter acts as a simple calculator.
The operators +, -, * and / work like you would expect
x%y
-x
abs(x)
pow(x, y)
x ** y
>>> a=5
>>> -a
-5
>>> abs(a)
5
>>> a**a
3125
remainder of x / y
x negated
absolute value of x
x to the power y
x to the power y
18
Number Operations
Binary operations on different numeric types
An operand with the “narrower” type is widened to that of the other,
Integer is narrower than long integer is narrower than floating point
is narrower than complex
>>> a =4
>>> b=10
>>> b/a #For integer division, the result is an integer.
2
By convention, integer division always rounds down
>>> a=4.0
>>> b/a
2.5
19
Booleans
Boolean values are the two constant objects False and True.
They are used to represent truth values
(other values can also be considered false or true).
>>> a=2
>>> b=3
>>> c=a==b
>>> c
False
>>>
20
Comparison Operations
Operation
Meaning
<
strictly less than
<=
less than or equal
>
strictly greater than
>=
greater than or equal
==
equal
!=
not equal
is
object identity
is not
negated object identity
Return True or False
>>> a<b
True
21
String Variables
Strings in Python are identified as a contiguous set of characters
in between quotation marks.
nameString = “My name is Kate”
Python allows for either pairs of single or double quotes.
nameString = ‘My name is Kate’
The same type of quote needs to start and end a string.
Strings are a sequence type and are indexed
Indexes start at 0 - the beginning of the string
22
String Operations
Operation
Result
x in s
True if an item of s is equal to x, else False
x not in s
False if an item of s is equal to x, else True
s+t
the concatenation of s and t
s * n, n * s
n shallow copies of s concatenated
s[i]
s[i:j]
ith item of s, origin 0
slice of s from i to j
s[i:j:k]
slice of s from i to j with step k
len(s)
min(s)
max(s)
length of s
smallest item of s
largest item of s
s.index(x)
index of the first occurrence of x in s
s.count(x)
total number of occurrences of x in s
23
String Operations
>>> namestring="My name is Kate"
>>> "M" in namestring # returns a Boolean
True
>>> "x" in namestring
False
>>> "x" not in namestring
True
24
String Operations
Concatenation is done with the + operator.
c = "Computing"
i= "Information Science"
cis = c+" & " + i
>>> cis
'Computing & Information Science'
Copies of string concatenated s * n, n * s
>>> c="Hooray"
>>> c *2
'HoorayHooray'
>>> 2*c
'HoorayHooray'
25
String Operations
len(string): returns the length of a string
s = "00000456"
len(s)
8
Min, max(string): returns first, last character of string
>>> c="Hooray"
>>> min(c)
'H'
>>> max(c)
'y'
26
String Operations
slice operator ( [ ] and [ : ] )
>>> namestring="My name is Kate"
>>> namestring
'My name is Kate'
>>> namestring[0]
'M'
>>> namestring[2:10]
' name is'
Indices may also be negative numbers, to start counting from
the right:
>>> namestring[-1] # last character
'e'
>>> namestring[-2:] # characters from the second-last (included) to the end
'te'
27
String Operations
slice operator ( [ ] and [ : ] )
Strings are immutable so namestring[2] = ‘a’ would cause an error
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
namestring[2]=a
TypeError: 'str' object does not support item assignment
28
String Operations
count operator str.count(sub[, start[, end]])
Returns the number of non-overlapping occurrences of
substring sub in the range [start, end].
s="running and jumping"
>>> s.count("ing")
2
>>> s2= s+ " and skipping"
>>> s2
'running and jumping and skipping'
>>> s2.count("ing")
3
29
String Functions
Strip -string strip([chars]): returns a copy of the string with
leading and tailing characters removed
s = "00000456"
t=s.strip("0")
t
'456'
By default strip removes all leading and trailing whitespaces
in a string.
>>> str = " this is string example...";
>>> print str.strip()
this is string example...
30
Comparison operations with strings
>>> c= "K"
>>> d= "Z"
>>> c>d
False
>>> c==d
False
>>> c<d
True
Based on alphabetical order
31
Casting Functions
int(variable) - casts variable to integer
c=10.5
int(c)
10
str(variable) - casts variable to string
track = "Track”
tracknum =10
track + (str)tracknum
float(variable) - casts variable to float
float(tracknum)
10.0
32
Some basic syntax rules for Python
Indentation is required in Python to logically group together
certain lines, or blocks, of code.
The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
if True:
print "True"
else:
print "False"
33
Python - Blank Lines
A line containing only whitespace, possibly with a comment, is
known as a blank line and Python totally ignores it.
In an interactive interpreter session, you must enter an empty
physical line to terminate a multi-line statement.
34
Python
syntax
35
Python syntax
Statements on multiple lines need to use a line continuation
character, which in Python is a backslash (\).
Python then interprets the line sequence as one statement.
total = item_one + \
item_two + \
item_three
If you use parentheses () or brackets [], Python understands that
you are continuing lines and no backslash is required.
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
36
Python syntax
The semicolon ( ; ) allows multiple statements on the single line
given that neither statement starts a new code block.
import sys; x = 'foo'; sys.stdout.write(x + '\n')
37
Python Modules
Modules are code saved in a reuseable form, a script.
They contain Python definitions and statements.
By convention, Python script files end with the extension .py.
Python has a large collection of standard modules, e.g file I/O,
system calls, sockets, and interfaces to graphical user interface
toolkits
Modules can be imported and reused in other Python programs.
38
Python Modules
Importing modules
import os, sys, math
>>> from math import sqrt , exp
>>> exp( -1)
0.36787944117144233
>>> sqrt (2)
1.4142135623730951
Module for using Python with ArcGIS
import arcpy
39
Commenting your Python code
Add a comment by beginning the line with a pound (#) sign.
Comments should explain what the code is doing.
Comments are ignored by Python, so you can add them at any
place in your code.
Comments help others who may have to work with your code
in the future; and they may even help you remember what the
code does
Your scripts should contain a heading section that describes
what it does, who created it, and when it was created, along
with comments throughout the script itself that explain what it is
doing.
40
Commenting your Python code
Single-line comments begin with the hash character ("#") and are
terminated by the end of line.
Python is ignoring all text that comes after the # to the end of the
line, they are not part of the command.
Comments spanning more than one line are achieved by inserting
a multi-line string (with """ as the delimiter on each end)
41
Commenting your Python code
'''---------------------------------------------------------------------------------Tool Name: ListFields
Source Name: ListFields.py
Version:
ArcGIS 10.4
Author:
Kate Beard
Required Arguements: input file
Description: prints out the fields and their properties
-------------------------------------------------------------------------------'''
import arcpy
#specify an input file
feature_class = "c:/old-c/AVdata/FireStations/fire.shp"
# Create a list of fields using the ListFields function
fields = arcpy.ListFields(feature_class)
# Iterate through the list of fields
for field in fields:
# Print field properties
print("Field:
{0}".format(field.name))
42
Specifying paths in Python
Paths are stored as string variables.
A backslash (\) is a reserved character indicating line continuation or an
escape sequence in Python. For instance, \n represents a line feed, \t
represents a tab.
When specifying a path, a forward slash (/) can be used in place of a
backslash. Two backslashes can be used instead of one to avoid a syntax
error.
Example 1: Valid use of paths in Python
fc = "C:/Data/Counties.shp“
Example 2: Invalid use of paths in Python
fc= (“C:\temp\streams.shp")
43