python intro - cpb-us-w2.wpmucdn.com · python intro jake k. carr. number types there are two main...
TRANSCRIPT
Python Intro
GIS 5222
Jake K. Carr
Week 1
Python Intro Jake K. Carr
Why Python
I It’s ‘simple’ and ‘easy’ to learn
I It’s free - open source!
I It’s cross platform
I IT’S ∞ expandable!!
Python Intro Jake K. Carr
Why Python: Example
Consider having to convert 1,000 shapefiles into feature classes ina geodatabase. We could run the appropriate tool (which is?)1,000 times, but there surely must be a much more efficient androbust way to do this.
With Python, we only need a handful of lines of code to carry outthis task.
Python Intro Jake K. Carr
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
Python Intro Jake K. Carr
Open Python:
There are lots of integrated development environments (IDEs) foraccessing Python. The default IDE that installs with ArcMap iscalled IDLE:
Python Intro Jake K. Carr
Help and Documentation:
Python comes with a few built in functions. To see what isavailable:
>>> 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’]
Python Intro Jake K. Carr
Basic Function: abs
Consider the basic function abs, which returns the absolute valueof 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! Usinghelp() tells you what ‘module’ the function is found in (builtin), aswell as the arguments that need to be passed to the function andthe output of the function.
Python Intro Jake K. Carr
Basic Function: dir
The basic function dir, which I often forget about, can be useful attimes. 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 nothingto you now, but it will in a bit.
Python Intro Jake K. Carr
Basic Function: range
The basic function range creates a list of indices. Used when tryingto 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 notenclosed in brackets - like stop - are required.
Python Intro Jake K. Carr
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 countsnumbers from 0 on, unlike humans, which tend to count from 1 on.
Python Intro Jake K. Carr
Object Assignment
Python is an Object Oriented Programming (OOP) language. Aswe saw above, we assign ‘things’ to objects. We have alreadyassigned things to the objects called rangelist, rangelist2, andrangelist3.
Object names have to follow specific guidelines - they can consistof letters, numbers, & underscores, but they cannot begin with anumber:
OK: range 2 to 11
Not OK: 2 range 11
Python Intro Jake K. Carr
Object Assignment
Cannot use designated keywords as object names. Note thatkeywords are highlighted in IDLE. For example, we can’t use printor import as an object name. Don’t give an object the same nameas 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.
Python Intro Jake K. Carr
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.
Python Intro Jake K. Carr
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
Python Intro Jake K. Carr
String Objects
So far, we have only assigned numbers to Python objects.Sometimes we will want to assign words to an object. Words arecalled character strings (or just strings) in programming talk andare contained in quote marks (single or double).
>>> mystring = "Hello"
>>> print mystring
Hello
String objects are also modifiable:
>>> mystring += " world."
>>> print mystring
Hello world.
Python Intro Jake K. Carr
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 insingle (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
Python Intro Jake K. Carr
More Strings
A quote in a string has to be placed inside a set of quotes usingthe 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
Python Intro Jake K. Carr
Data Types
Python objects can contain more than one piece of information (orone piece of data). There are three types of Python object forstoring data: lists, tuples and dictionaries.
I A list is just a list of objects, which can be modified.
I A tuple is a list of objects that can’t be modified (so they aremore efficient then lists).
I A dictionary is a list of objects in which each object is givenan identifier.
Lists are created with square brackets [], tuples with parentheses(), and dictionaries are created with curly brackets {}.
Python Intro Jake K. Carr
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’>
Python Intro Jake K. Carr
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’>
Python Intro Jake K. Carr
Indexing List Items
We can access or modify items in a list using its index. Index isjust a word that means position in the list. Recall that Pythonstarts counting at 0, therefore indexes begin with 0 - not 1.
>>> mylist = [1, ["another", "list"], ("a", "tuple")]
>>> mylist [0]
1
>>> mylist [1]
[’another ’, ’list’]
Python Intro Jake K. Carr
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 fromthe back of the list.
Python Intro Jake K. Carr
Dictionaries
A dictionary is a list of items (called ‘values’) which are identifiedby a ‘key’. The ‘values’ are indexed by the ‘key’ it is associatedwith - 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}
Python Intro Jake K. Carr
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)
Python Intro Jake K. Carr
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 calledmyfunction.
Python Intro Jake K. Carr
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 thatPython will slice in increments of N instead of 1.>>> print mylist [0:3:2]
[’List_item_1 ’, 3.14]
Python Intro Jake K. Carr
String Slicing
String objects can be sliced and diced as well, but there isadditional functionality associated with strings that can sometimesbe very handy: word reversing.
>>> word = ’abcdef ’
>>> word [::-1]
’fedcba ’
>>> word = ’science ’
>>> word [::-1]
’ecneics ’
Python Intro Jake K. Carr
More Strings
Strings are often useful for creating messages in your code. Wecan convert numbers into a string object and ‘concatenate’ theresulting string to other strings.
>>> temp = 100
>>> print temp
100
>>> print "The temperature is " + str(temp) + " degrees today."
The temperature is 100 degrees today.
Python Intro Jake K. Carr
Concatenating Lists
One of the nice features about lists is that they are easilyappended - 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]
Python Intro Jake K. Carr
Number Types
There are two main types of numbers, integer and float. Integersare whole numbers, floats are numbers with decimals. In olderversions of Python arithmetic between two integers would result ininteger values, so one of the integers would have to be forced intoa float type for complete accuracy.
>>> 3/1
3
>>> 10/3
3
>>> 10.0/3
3.3333333333333335
>>> 10/3.0
3.3333333333333335
Python Intro Jake K. Carr
Comparisons
In many programming applications we need to compare two (ormore) values and then execute a command depending on thecomparison. The result of a comparison is either True or False:
>>> a = 21
>>> b = 10
>>> a == b
False
>>> a != b
True
Python Intro Jake K. Carr
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
Python Intro Jake K. Carr