Python
Python is a versatile and widely used language. It can be used for data processing/data mining, web development, and inside of ESRI's ArcGIS environment. The documentation is extensive and there are numerous libraries to help make your life easier.
print
statement in the window. You should see it print to the lower right after clicking the "run"/"play" button.=
print
statement assign that variable to a new value and print
it again.<Code>
#print statement
print "Oh hi there! This is a python print statement!"
#variable assignment
var = 123
var_int = 123
var_float = 1.23
var_bool = True
Functions
Functions are a set of organized and reusable code. You're already familiar with one of Python's built in funcitons - print
. Python has numerous built in functions, but you can also define your own. Functions in Python follow a consistent structure
def
followed by the function name, parentheis and a colon (def function(parementer1,parameter2):
return
statement will exit the function and return any variables/data you want as an output.def
and call it multiply
multiply(3,5)
. What happens? What if you add a print
statement before calling the multiply
function?<Code>
def multiply(number1,number2):
newNumber = number1 * number2
return newNumber
multiply(3,5)
You're already somewhat familiar with math operations from creating the multiply
function
add
(add two numbers)subract
(by subtracting two numbers)multi
(multiply two numbers)divide
(divide two numbers)power
(raise one number to the power of another)remainder
(use the %
(modulo) to get the remainder of a division operation)print
your variables<Code>
add = 123 + 456
subract = 456 - 123
multi = 5 * 4
divide = 9 / 4
power = 5 ** 6
remainder = 9 / 4
print add, subract, multi, divide, power, remainder
barTab = 15.75
tax = 0.0675
tip = 0.18
#calculate the total bill
barTotal =
print barTotal
print
the string'text'
) or double quotes "text"
. But, if an apostrophe (single quote) occurs in the string contained by single quotes you need a \
before it.[]
to access characters at a specific index in a string, or to access part of a string
len()
function to determine the length of a string. Assign that length to the variable stringLength
and print
it..upper()
and .lower()
to convert as string to all upper case or all lower case.str()
.+
operation.%s
place holder in a string with %(variable_to_put_in_string)
.raw_input('enter some text: ')
to get input from the user and insert into a string using the %s
.<Code>
#text variable
text = 'The Dude Abides'
#adding apostrohpe inside string with double quotes using \
dudeRug = 'That\'s the Dude\'s rug!'
#print specific indices
ind1 = text[0]
indLast = text[-1]
indMiddle = text[1:5]
print ind1, indLast, indMiddle
#text length
textLength = len(text)
textUpper = text.upper()
textLower = text.lower()
print textUpper, textLower
number = 123
numberString = str(number)
print numberString
#string concantenation
concat1 = 'The' + 'Dude' + 'Abides'
concat2 = 'The answer to the Universe is: ' + str(42)
concat3 = 'That %s really tied the %s together Dude.' %('rug','room')
name = raw_input("What's your name? " )
print "Hi %s. I'm HAL" %(name)
ls = []
.append(item)
method add an integer, decimal, string, and boolean to the listprint len(ls)
ls[index]
.pop
and set it equal to a variable.ls.insert(index, thing)
tup = ()
tup
variable as you did on the ls
varible and see what happens (Explanation)d = {}
d["Jeff Bridges"] = 'The Big Lebowski'
. A new dictionary entry is created by in using brackets for the key, an equal sign, and the associated value.d["Jeff Bridges"] = ('The Big Lebowski','Tron')
<Code>
ls = []
ls.append(1)
ls.append(1.23)
ls.append(True)
ls.append("Bunny's pinky toe")
print ls
ls_len = len(ls) #list length
print ls_len
#You access items in a list by their index, starting at 0 for the first item.
#The last item of a list can be accessed using the -1 index, or the length of the list
print ls[0],ls[-1]
#remove the last item
removed = ls.pop() #remove the string "Bunny's pinky toe"
ls.insert(1,removed)
print ls
#tuples
tup = ()
#What happens when you try append?
#dictionaries
d = {}
d["Jeff Bridges"] = "The Big Leboswki"
d["Bruce Willis"] = "The Fifth Element"
d["Keanue Reeves"] = "John Wick"
d["Nicolas Cage"] = "Con Air"
d["Simon Pegg"] = "Shaun of the Dead"
print d, d["Simon Pegg"]
You're already likely familiar with comparisons. The <
is an example of a comparison. Comparisons result in a boolean variable True
or False
.
==
(equal to)!=
(not equal to<
or >
(less than or greater than)<=
or >=
(less/greater than or equal to.True
change the values or comparison signs so they evalute False
.and
and or
operators can be used in conjunction with comparisons to use multiple arguments. Below is a table of how these operate and the boolean variable they create.
or Table |
|||
---|---|---|---|
Statement 1 | operator | Statement 2 | True or False? |
True |
or |
True |
True |
True |
or |
False |
True |
False |
or |
True |
True |
False |
or |
False |
False |
and Table |
Statement 1 | operator | Statement 2 | True or False? |
True |
and |
True |
True |
True |
and |
False |
False |
False |
and |
True |
False |
False |
and |
False |
False |
not
operator reverses the boolean created by the statement following it. #Exercises
to make them evaluate correctly based on the comment above them.<Code>
b1 = 25 ==5**5
b2 = 4 != 5
b3 = 72 < 43
b4 = 72 > 43
b5 = 25 >= 25
print b1, b2, b3, b4, b5
bAnd1 = 1> 2 and 2 > 3
bAnd2 = True and False
bAnd3 = False or True
bAnd4 = True and 4*3 > 10
bAnd5 = 2 ==2 and 3 == 5
print bAnd1, bAnd2, bAnd3, bAnd4, bAnd5
bOr1 = 1 > 2 or 2 > 3
bOr2 = True or False
bOr3 = False or 1 == 1
bOr4 = True or 2 > 5
bOr5 = 2 == 2 or 4 == 3
print bOr1, bOr2, bOr3, bOr4, bOr5
bNot1 = not 2 > 3
bNot2 = not True
bNot3 = not 3 > 2
bNot4 = not 2 == 3
print bNot1, bNot2, bNot3, bNot4
#Exercises for you
#Make me False
b1 = 1 > 2 and 3 == 3
#make me true
b2 = 1 > 0 and not True
#make me false
b3 = not True or 3 == 3
#make me True
b4 = not False and 3*4 != 12
#make me False
b5 = 1 != 2 and 1 == 1
Comparisons evalute one thing to another, or check if something is true. Here we'll learn if
, and
, and or
statemetns.
if
check if the variable is less than 10else
after the if
statement we can assign another task if the the if
condition isn't satisfiedif
statement in the form of elif
. elif
is short hand for "else if". If the first if
isn't statisfied, but you have more than one thing to check for you can use elif
. You can use as many elif
s as you like before the final else
.elif
after the if
to check if the number is less than 5<Code>
var = #pick a number
if var < 10:
print 'Far out man! %s is less than 10!' %s(var)
else:
print "That's a real bummer man. A number less than 10 really ties the room together..."
Using what you've learned we'll make a Pig Latin translator that takes a string as input from the user and translates it to Pig Latin using conditional statements.
print
statement welcoming the user to the Pig Latin translatorlen()
function..isalpha()
. Add this to the first if
condition using an and
. Click here for a hint.lower()
. Why don't you do this sooner?[]
at the end of the word/string variable with a number inside to accees a character at a particular index of a string.<Code>
#Pig Latin Translator
print "Welcome to the Pig Latin Translator"
#get word from user
word = raw_input("Please type a word for translation. ")
if #insert your conditions after the "if" followed by a colon to check for word length and validity
print word + ' appears to be a real word'
firstLetter = word[]#insert the correct index in the brackets
otherLetters = word[:]#insert the correct numbers before and after the colon to get the rest of the word
list_of_vowels = [] #create a list of vowels inside the brackets. each letter must be enclosed in quotes
if ## in list_of_vowels: #insert the correct variable in the double hashtags
print #print the pig latin translation here
else:
print #print the pig latin translation for a word that begins with a consonant.
else:
print "sorry. You didn\'t follow directions. %s is not a real word" %(word)
loops
Working with loops and understanding how to structure them is how you leverage programming skills into working for you - reducing monotous work. You can loop through thousands of lines of data looking for specific occurences or data types in seconds. You can add conditional statements to loops, do loops within loops. We'll work with small lists to get the hang of working with loops. The structure is the same no matter if you have a list/array of 5 data points or 5 million.
raw_input
is a string using .isalpha()
if else
statement to print a statement for each condition.comp1
evalute to True
comp2
evaluate to False
using an and
statementcomp3
evalute to True
using an or
statement.upper()
notation.
[]
notation<Code>
#variable to get input from user
var = raw_input('Type a string. Any string you like. So long as it\'s a string: ')
#define/create function
def function(variable):
if variable.isalpha():
print "Thank you! You typed a string"
else:
print "False! That's not a string!"
#call function
function(var)
#create three comparison variables
comp1 = #evaluates to True
comp2 = #evalutes to False using 'and'
comp3 = #evaluates to True using 'or'
print comp1, comp2, comp3
#string variable
s = 'I\'m the Dude. You\'re Mr. Lebowski!'
s1 = s[0] #acces first letter using brackets
for
LoopsLoops are way of iterating through lists, arrays, strings, and the like. You can loop through and look for certain variables, perform an operation on all of them, or any number of other things. Understanding loops is a fundamental lesson in programming.
for
accessor, loop through your list and print each variable.thing
" is just a place holder. Commonly i
is used in loops (i.e. For i in ls:
).**
.append(thing)
accessor to do thisIf you want to challenge yourself click here
for
loop to print the thing if the thing is a digit.
int
)type(variable)
to determine the type for each thing in listor
to the if
conditional statement to check if a list element is a float.elif
to check of a variable is a boolean (True
or False
)
elif
to check of an element is text using .isalpha()
click for hint if you're noticing a problem with one of the outputs of the loop
<Code>
ls = [1,True,'text',1.23,'Some more text']
for thing in ls:
print thing
#modified loop
for thing in ls:
if type(thing) == int:
print '%s is a number' %(thing)
else:
print '%s is not a number' %(thing)
for i in range()
LoopsThe for i in range()
loop type is a bit different than the standard for i in ...
loop. Think of for i in range()
as accessing the index of an array of elements. As an example, we'll do two of these loops with one small difference. you can read more about the range function here.
for
loop section, except use the for i in range(len(list_variable))
.The built in range()
function combined with a for
loop will iterate the number times as your list is long which is fed into the range function. range(len(list_variable))
and print it. How many elements are in the list?<Code>
#use the for i in range loop on a list
for i in range(len(list_variable)):
print i
list_range = range(len(list_variable)
print list_range
#print element and index
for i in range(len(list_variable)):
print '%s is at index: %s' %(list_variable[i],i)
while
LoopsA while
loop will continue to as long as a condition is true. This can be dangerous. If you don't specify how to break the loop it will continue infinitely - hence the term infinte loop. Much like the "revolving door of experience" where you can't get a job w/o experience, but you need a job to get experience...
import random
.while
loop that will continue to append random numbers to a list until the list length is greater than 10
bool
variable and set it to True
while
with your boolean condition. if
to check the list length. If it's >= 10
set your continue variable to False
.<Code>
#import random library
import random
#print a random number between 0 and 100
#numbers in the parenthesis are the lower, and upper bounds
#of where you want a random number created
print random.randint(0,100)
#empty list
ls = []
#create a boolean variable
while addNumbers:
#your while loop contents will go here!
Here's a challenge for you. You don't have to tackle this, as with the entire class - it's optional. Create a list of 20 random numbers between 0 and 20 using the while
loop from the last section. Now, define a function called targetCounter that takes two arguments as input def targetCounter(list_variable,target)
. This function will count the number of times your target occurs in the list of random numbers. So, the steps are as follows:
targetCounter
that takes a list and number as argumentsfor
loop.
if
conditional statementcounter += 1
counter = counter + 1
click here for solution (after you've at least given it the old "college try"...
Let's dive in to the deep end and start working with a CSV, which will be avaialble on the repl.it site. We will open the CSV and look for locations that are within the North American Bounding geographic bounding box and append those names to a new list. This is just a list of randomly generated names and locations.
with open("file name in quotes", "r") as f
:
with
only keep the file open for as long as we need to iterate through it. No need to close it after we're done. It's nice, neat, and tidy.open()
as the name implies, opens the file, and the as f:
assigns that open file to a variable.reader = csv.reader(f)
(with f being the open csv file)next(reader, None)
. It will skip the first row.for
loop we'll iterate through all the rows in the reader object and look for locations within the North American bounding box.
if
statment...if
condition is satisfied, create a tuple varible containing the first name, last name, lat, and lon and append it to the list being used to track these locations.<Code>
import csv #import the csv library
#Geographic Bounding box of North America(ish)
top = 72.471968 # north lat
left = -168.222656 # west long
right = -47.988281 # east long
bottom = 12.801088 # south lat
#empty list
NA_locations = []
with open("csv name here","r") as f:
reader = csv.reader(f) #create a reader object
next(reader, None) #skip header
#iterate through rows looking for locations within North American Bounding Box
for row in reader:
#access the index of lat and lon using row[index] and assign lat and lon variables
#make sure to convert them to a float. All data will be read in as a string unless
#until converted
lat =
lon =
#string together comparisons to create one if statment checking if the location is within the bounding box
if check for lat and check for lon:
name = (tuple of data to append to NA_locations)
NA_locations.append(name)
#You should get a list of 7 people/locations..
print NA_locations, len(NA_locations)
Functions
This week we'll work on putting together lessons from the past three weeks to create some function's that will challenge you to think "programatically" - basically figuring out the steps required to get the desired outcome.
int
. Just encase they entered a decimal for some reason.print
a string for the if
and else
function respectivelyraw_input
statement to something like "I'm thinking of a number between 1 and 10 (inclusive)". Guess a number.random
library to randomly select an element from the list.print
"You chose...poorly".<Code>
#import random library
import random
#define the function
def numberGuesser():
numberList = []#insert numbers 1 - 10 here
#randomly select a number from the list you created
number = random.choice(#put the numbers list variable here)
guess = raw_input("I'm thinking of a number between 1 & 10 (inclusive). Guess a number: ")
#use a 'nested if' to check if that guess is the number
if number == guess:
print "Lucky Guess"
else:
print "You chose...poorly"
#call the function
numberGuesser()
What if we wanted to give someone more than just 1 chance to guess a number. Here we'll work to modify the function you just wrote to track guesses and allow the user to guess up to 3 times.
counter
.while
loop so the function will continue to ask for a guess from the user so long as our counter < 3
It'd be nice to provide feedback to the user after a guess regarding if the numbrer they guessed is too high or too low. Let's add that functionality to the function
if
statement in the function you've built thus far. But, we'll re-arrange the order of the if conditions.if
to anelif
if
to check if the guess is greater than the number and if the counter < 3. If so, print "Guess too high, you did!"
. **We only want these two statemetns to trigger if the counter is less than 3, so on the third guess they won't be triggered**.elif
to check if the guess is less than the number and if the counter < 3. If so, print "Guess too low, you did!"
What if the game is just too much fun and you want to keep guessing? Let's add an option to ask for more guesses by nesting another if
statement inside the last else
condition..
else
statment add another raw_input
statement asking the user if they would like more guesses.<Code>
#import random library
import random
#define the function
def numberGuesser():
numberList = []#insert numbers 1 - 10 here
#counter variable
counter = 0
#randomly select a number from the list you created
number = random.choice(#put the numbers list variable here)
#while loop
while #insert your condition here
guess = raw_input("I'm thinking of a number between 1 & 10 (inclusive). Guess a number: ")
#increment counter here
#use a 'if' to check if guess is the number
if number == guess:
print "Lucky Guess"
else:
print "You chose...poorly"
#call the function
numberGuesser()
Do you have a hard time making decision? Do you find carrying around a "Magic 8 ball" cumbersome to help you with your indecisiveness? If so, you can create a small function to help you make decisions that's much lighter than a Magic 8 Ball. (It's esier than the number guesser)
magicBall
answerList
with the following responses:
random.choice()
function and print it.<Code>
import random
#define function
def magicBall():
question = #prompt user to type quesiton with raw_input
responses = [] #fill this list with responses
answer = #randomly choose item from the response list using random.choice list
print answer
#call function
magicBall
ArcPy
ArcPy is the python library used in ESRI's software (ArcMap, ArcCatalog, etc). You can open a python interepreter inside of ArcMap and test ideas or hash out short loops and scripts. Or, you can write longer scripts and create tools/scripts for repeated use.
To start let's create some random points inside the state of Iowa. Go to the Iowa NRGIS Library and grab a state boundary shapefile for Iowa
<Code>
#This will be done inside the python window of arcMap
#define output path for ease
outPath = "C:\Users\Your_HAWKID\Documents\ArcGIS\Default.gdb"
outName = 'Iowa_Random_Points'
numPoints = 100
arcpy.CreateRandomPoints_management(outPath,outName,IowaShapeFileHere,,numPoints,,"MULTIPOINT")
This can be done in the "table view", but it can also be done in the python window...
<Code>
#This will be done inside the python window of arcMap
#define output path for ease
arcpy.AddField_Management("InTable","FieldName","TEXT")
#This part will actually be done in the field calculator.
#We don't need any input so nothing goes in the parenthesis
def randNumber():
#import just the random integer part of the random library
from random import randint
#generate a randon mumber between 5 and 25
randNumber = randint(5,25)
#create a string combining that random number and the text Miles.
text = str(randNumber) + " MILES"
return text
We'll use python in the field calculator to create a random integer between 5 and 25 in a field
<Code>
#This will be done inside the python window of arcMap
#define output path for ease
outName = "RandPoints_Buffer"
DistanceField = "BufferDistance"
arcpy.Buffer_analysis(randomPoints,outName,DistanceField,,,"ALL")