GIS 5222 Week 1
Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!!
Why Python: Example Consider having to convert 1,000 shapefiles into feature classes in a geodatabase. We could run the appropriate tool (which is?) 1,000 times, but there surely must be a much more efficient and robust way to do this. With Python, we only need a handful of lines of code to carry out this task.
Learning Python: Many, many online sources. See the manual posted to Carmen. General Python: Stavros: http://www.stavros.io/tutorials/python/ Python for ArcGIS: Penn State: https://www.e-education.psu.edu/geog485
Open Python: There are lots of integrated development environments (IDEs) for accessing Python. The default IDE that installs with ArcMap is called IDLE:
Help and Documentation: Python comes with a few built in functions. To see what is available: >>> print dir ( builtins ) There are many basic functions included in base Python: [ abs, dir, help, len, max, min, pow, print, range, reversed, round, slice, sorted, sum ]
Basic Function: abs Consider the basic function abs, which returns the absolute value of the numeric argument passed to it. >>> help ( abs ) Help on built - in function abs in module builtin : abs (...) abs ( number ) -> number Return the absolute value of the argument. Note that help (used above) is also a basic built in function! Using help() tells you what module the function is found in (builtin), as well as the arguments that need to be passed to the function and the output of the function.
Basic Function: dir The basic function dir, which I often forget about, can be useful at times. It returns the attributes associated with an object. >>> help ( dir ) Help on built - in function dir in module builtin : dir (...) dir ([ object ]) -> list of strings The attributes associated with an object probably means nothing to you now, but it will in a bit.
Basic Function: range The basic function range creates a list of indices. Used when trying to enumerate a set of objects. >>> help ( range ) Help on built - in function range in module builtin : range (...) range ([ start,] stop [, step ]) -> list of integers Any function argument enclosed in brackets - like [start,] - indicates that that argument is optional. Arguments that are not enclosed in brackets - like stop - are required.
Basic Function: range Here we create 3 different lists of indices using the range function. How do these lists differ? >>> rangelist = range (2,11,4) >>> print rangelist [2, 6, 10] >>> rangelist2 = range (2,11) >>> print rangelist2 [2, 3, 4, 5, 6, 7, 8, 9, 10] >>> rangelist3 = range (11) >>> print rangelist3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] What happened in rangelist2 and rangelist3? Python counts numbers from 0 on, unlike humans, which tend to count from 1 on.
Object Assignment Python is an Object Oriented Programming (OOP) language. As we saw above, we assign things to objects. We have already assigned things to the objects called rangelist, rangelist2, and rangelist3. Object names have to follow specific guidelines - they can consist of letters, numbers, & underscores, but they cannot begin with a number: OK: range 2 to 11 Not OK: 2 range 11
Object Assignment Cannot use designated keywords as object names. Note that keywords are highlighted in IDLE. For example, we can t use print or import as an object name. Don t give an object the same name as a function! Python in general is CASE sensitive! >>> Rangelist = range (11) >>> print Rangelist [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> rangelist = range (12) >>> print rangelist [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> Rangelist == rangelist False Rangelist is not the same object as rangelist.
Object Assignment Assignments are modifiable: >>> myvar = 3 >>> print myvar 3 >>> myvar += 2 >>> print myvar 5 >>> myvar -=1 >>> print myvar 4 We ll refer to (+=) or (-=) as a Modify & Assign Operation.
Object Assignment We can make multiple assignments in one line!! >>> var1, var2 = 4, 34 >>> print var1 4 >>> print var2 34 We can even swap assignments in one line!!! >>> var1, var2 = var2, var1 >>> print var1 34 >>> print var2 4
String Objects So far, we have only assigned numbers to Python objects. Sometimes we will want to assign words to an object. Words are called character strings (or just strings) in programming talk and are contained in quote marks (single or double). >>> mystring = " Hello " >>> print mystring Hello String objects are also modifiable: >>> mystring += " world." >>> print mystring Hello world.
More Strings Strings are enclosed in either single quotes or double quotes. If you open a string in single (double) quotes you need to end it in single (double) quotes. >>> string = I like turtles SyntaxError : invalid syntax >>> string = " He said hello " >>> print string He said hello >>> string = He said hello >>> print string He said hello
More Strings A quote in a string has to be placed inside a set of quotes using the opposite punctuation than that used to open/close the string >>> string = " He said hello " >>> print string He said hello >>> badstring = " He said " hello "" SyntaxError : invalid syntax
Data Types Python objects can contain more than one piece of information (or one piece of data). There are three types of Python object for storing data: lists, tuples and dictionaries. A list is just a list of objects, which can be modified. A tuple is a list of objects that can t be modified (so they are more efficient then lists). A dictionary is a list of objects in which each object is given an identifier. Lists are created with square brackets [], tuples with parentheses (), and dictionaries are created with curly brackets {}.
Lists A modifiable list of items (objects). >>> mylist = [1, 2, 3.14] >>> print mylist [1, 2, 3.14] >>> type ( mylist ) <type list > The items don t have to be the same type (numbers and strings): >>> mylist = [" item_1 ", 2, 3.14] >>> print mylist [ item_1, 2, 3.14] >>> type ( mylist ) <type list >
Lists We can even have a list of lists: >>> mylist = [1, [" another ", " list "], ("a", " tuple ")] >>> print mylist [1, [ another, list ], ( a, tuple )] >>> type ( mylist ) <type list >
Indexing List Items We can access or modify items in a list using its index. Index is just a word that means position in the list. Recall that Python starts counting at 0, therefore indexes begin with 0 - not 1. >>> mylist = [1, [" another ", " list "], ("a", " tuple ")] >>> mylist [0] 1 >>> mylist [1] [ another, list ]
Indexing List Items We can replace an item in a list using an indexed assignment: >>> mylist = [1, [" another ", " list "], ("a", " tuple ")] >>> mylist [0] = 4 >>> print mylist [4, [ another, list ], ( a, tuple )] >>> mylist [ -1] = 3.21 >>> print mylist [4, [ another, list ], 3.21] Notice that a negative index (fifth line) tells Python to start from the back of the list.
Dictionaries A dictionary is a list of items (called values ) which are identified by a key. The values are indexed by the key it is associated with - not the index number like with lists. >>> mydict = {" Key_1 ": " Value_1 ", 2: 3, "pi": 3.14} >>> print mydict { Key_1 : Value_1, 2: 3, pi : 3.14} >>> print mydict [ pi ] 3.14 Modifications are assigned with the key as well. >>> mydict [" pi"] = 3.999 >>> print mydict { Key_1 : Value_1, 2: 3, pi : 3.999}
Tuples Tuples are just light-weight lists. You can t modify them. >>> mytuple = (1, 2, 3) >>> print mytuple (1, 2, 3) >>> mytuple [0] 1 >>> mytuple [0] = 4 Traceback ( most recent call last ): File " < pyshell #76 >", line 1, in <module > mytuple [0] = 4 TypeError : tuple object does not support item assignment >>> print mytuple (1, 2, 3)
Other Assignments You can even assign a function to an object! >>> myfunction = len >>> print myfunction ( mytuple ) 3 Here we have assigned the length function to the object called myfunction.
Index Slicing To index over a consectutive set of items we use index slicing, which is accomplished by stating a start position and a read count, seperated by a colon (:). >>> mylist = [" List_item_1 ", 2, 3.14] >>> print mylist [:] [ List_item_1, 2, 3.1400000000000001] >>> print mylist [1:] [2, 3.14] >>> print mylist [0:2] [ List_item_1, 2] >>> print mylist [ -3:1] [ List_item_1 ] If we add a second colon we can specify the step count, so that Python will slice in increments of N instead of 1. >>> print mylist [0:3:2] [ List_item_1, 3.14]
String Slicing String objects can be sliced and diced as well, but there is additional functionality associated with strings that can sometimes be very handy: word reversing. >>> word = abcdef >>> word [:: -1] fedcba >>> word = science >>> word [:: -1] ecneics
More Strings Strings are often useful for creating messages in your code. We can convert numbers into a string object and concatenate the resulting string to other strings. >>> temp = 100 >>> print temp 100 >>> print " The temperature is " + str ( temp ) + " degrees today." The temperature is 100 degrees today.
Concatenating Lists One of the nice features about lists is that they are easily appended - you can add items to a list without re-defining the list. >>> mylist = [" List_item_1 ", 2, 3.14] >>> print mylist [ List_item_1, 2, 3.1400000000000001] >>> mylist + [13] [ List_item_1, 2, 3.1400000000000001, 13] >>> print mylist [ List_item_1, 2, 3.1400000000000001] >>> mylist = mylist + [13] >>> print mylist [ List_item_1, 2, 3.1400000000000001, 13]
Number Types There are two main types of numbers, integer and float. Integers are whole numbers, floats are numbers with decimals. In older versions of Python arithmetic between two integers would result in integer values, so one of the integers would have to be forced into a float type for complete accuracy. >>> 3/1 3 >>> 10/3 3 >>> 10.0/3 3.3333333333333335 >>> 10/3.0 3.3333333333333335
Comparisons In many programming applications we need to compare two (or more) values and then execute a command depending on the comparison. The result of a comparison is either True or False: >>> a = 21 >>> b = 10 >>> a == b False >>> a!= b True
Comparisons We can even make comparisons with items in a list: >>> mylist = [ List_item_1, 2, 3.14] >>> 4 in mylist False >>> 2 in mylist True