Week 1

Introduction to 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.


Variables

  1. Create a new document in Wing and enter a print statement in the window. You should see it print to the lower right after clicking the "run"/"play" button.
  2. Assign a number to a variable using the =
  3. Create three more variables
    1. Integer (no decimal)
    2. Floating point (decimal)
    3. Boolean (true or false)
  4. print one of your integer variables, below the print statement assign that variable to a new value and print it again.
  5. The variable types we'll be using most frequently are:
    • Numeric (integer or float/decimal)
    • String (text)
    • List (hopefully this needs no explanation)
    • Boolean (True or False)
    • Dictionary (more on this later)
    • Tuple (similar to a list, with one key difference)

<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

  1. Create a new function using def and call it multiply
  2. Have this function take two numbers as arguments
  3. Inside the function multiply the first number by the second and return it
  4. Call the function 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)



Math Operations

You're already somewhat familiar with math operations from creating the multiply function

  1. Create the following variables:
    1. add (add two numbers)
    2. subract(by subtracting two numbers)
    3. multi (multiply two numbers)
    4. divide (divide two numbers)
    5. power (raise one number to the power of another)
    6. remainder (use the %(modulo) to get the remainder of a division operation)
  2. print your variables
  3. Use some math operations to figure out your bar tab:
    1. bar tab is 15.75
    2. local sales tax is 6.75% (0.0675)
    3. you tip generously at 18%

<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


Strings

  1. Create a string variable and set it equal to some text.
  2. print the string
  3. Strings can be contained in single quotes ('text') or double quotes "text". But, if an apostrophe (single quote) occurs in the string contained by single quotes you need a \ before it.
  4. You can use [] to access characters at a specific index in a string, or to access part of a string
    1. access the first character of one of your string variables
    2. access the last character of one of your string variables
    3. access the 2nd through the 5th character in your string (hint)
  5. Use the len() function to determine the length of a string. Assign that length to the variable stringLength and print it.
  6. Use the .upper() and .lower() to convert as string to all upper case or all lower case.
  7. Convert a number to a string using str().
  8. String Concatenation
    1. strings can be concantenated using the + operation.
    2. convert a number to a string and concantenate it with another string.
    3. You can also use a place holder in a string to fill it in later. This is useful for putting numbers in strings w/o converting them to a string first. Use the %s place holder in a string with %(variable_to_put_in_string).
  9. Use the 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)



Lists, Tuples, and Dictionaries

  1. A list is a set or collection of comma seprated values. Lists can be all the same data type, or a collection of diffferent data types.
    1. Create an empty list equal to a variable ls = []
    2. Using the .append(item) method add an integer, decimal, string, and boolean to the list
    3. print the length of the list using print len(ls)
    4. Print the first and last item in the list, accessing them by index using brackets ls[index]
    5. Remove the last item in the ls using .pop and set it equal to a variable.
    6. Insert the removed item into the second index (index number 1) using the ls.insert(index, thing)
  2. A Tuple is a series of immutable variables/objects that behaves much like a list, but has a few different properties. Create a tuple variable and tup = ()
    1. Try the same set of insructions on the tup variable as you did on the ls varible and see what happens (Explanation)
  3. Creat a dictionary variable d = {}
    1. A dictionary is a set of key, value pairs. Dictionaries can be useful when trying to classify data into groups, or when just trying to keep track of related data.
    2. Create a series of dictionary entries of actors and a movie they've been in (i.e. 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.
    3. Recreate your dictionary now, with two or more movies associazted with each actor using the tuple variable type. (i.e. d["Jeff Bridges"] = ('The Big Lebowski','Tron')
    4. Pick a dictionary entry and access the second associatea movie for an entry (i.e. d["Jeff Bridges"][1] where the bracketed 1 is accessing the second item associate with the Jeff Bridges entry)

<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"]




Comparisons

You're already likely familiar with comparisons. The < is an example of a comparison. Comparisons result in a boolean variable True or False.

  1. Create variables that are assigned to a comparison statement
    1. Use the == (equal to)
    2. Use the != (not equal to
    3. Use the < or >(less than or greater than)
    4. use the <= or >=(less/greater than or equal to.
  2. As an exercise change the b1 through b5 variables so that they now evalaute oppostite of their original value (if originally True change the values or comparison signs so they evalute False.
  3. The 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
  4. The not operator reverses the boolean created by the statement following it.
  5. Work through the b1 through b5 variables under the #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



More Comparisons

Comparisons evalute one thing to another, or check if something is true. Here we'll learn if, and, and or statemetns.

  1. Create a numeric variable that is an intiger between 1 and 20.
  2. Using if check if the variable is less than 10
  3. using else after the if statement we can assign another task if the the if condition isn't satisfied
    1. Now, let's ammend the conditional statment you just created by adding another if 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 elifs as you like before the final else.
    2. Add an 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..."




Pig Latin Translator

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.

  1. Start with a print statement welcoming the user to the Pig Latin translator
  2. Create a variable that asks the user to input a word
    1. Check that the word has a length greater than 1 using the len() function.
    2. if word given by the user doesn't have a length greater than 1, print a statement alerting the user
  3. Check that the word is a word using .isalpha(). Add this to the first if condition using an and. Click here for a hint
  4. inside the condtion checking for word length and validity, convert the word to all lower case using .lower(). Why don't you do this sooner?
  5. Save the first letter in the word to a new variable (i.e. "firstLetter"). You can use the [] at the end of the word/string variable with a number inside to accees a character at a particular index of a string.
  6. save all but the first letter of the word to another variable (i.e. "otherLetters").
  7. For Pig Latin, you translate word depending on the first letter
    1. if the first letter is a vowel, the tranlstion is simply word + "ay" ending.
    2. If the first letter is a consonant the translation is: (word - first letter) + first letter + "ay"

<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)




Week 2

Working with 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.

Review

  1. Start by creating a function that takes input from the user.
    1. Check that the raw_input is a string using .isalpha()
    2. Use an if else statement to print a statement for each condition.
    3. Test your function by calling it.
  2. Create three variables that are comparisons
    1. Have comp1 evalute to True
    2. Have comp2 evaluate to False using an and statement
    3. Have comp3 evalute to True using an or statement
  3. Create a string variable and convert it to all upper case using .upper() notation.
    1. Access the first letter of the string using the [] notation
    2. Access the last letter of the string
    3. Create new string with the first and last letter swapped

<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 Loops

Loops 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.

  1. Create a list with 5 elements in it. They can be numbers, strings, booleans, anything you like.
    1. Using the for accessor, loop through your list and print each variable.
  2. **You'll notice the "thing" is just a place holder. Commonly i is used in loops (i.e. For i in ls:).**
  3. Append two more elements to your list. They can be any data type so long as one of them is a float (i.e. 1.23). use the list.append(thing) accessor to do this

  4. If you want to challenge yourself click here

  5. Modify your for loop to print the thing if the thing is a digit.
    1. To check if a variable is numeric you need to check if it's an integer (int)
    2. Use the type(variable) to determine the type for each thing in list
    3. If the type is a number print a string notifying the user that it's a number. If not, print a string notifying it isn't
    4. **You'll notice that the float number isn't evaluated as a number...**
    5. Add an or to the if conditional statement to check if a list element is a float.
  6. Add an elif to check of a variable is a boolean (True or False)
    1. Add a print statement to this condtion similar to those in step 3.3
  7. Add another 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() Loops

The 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.

  1. You can use the same list you created for in the 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.
  2. As an exercise, create a variable equal to the range(len(list_variable)) and print it. How many elements are in the list?
  3. Modify your loop so that for each element in the list it will print the element and the index where it is in the list.
  4. Modify the loop so it prints the variable, type and index
  5. Modify the loop so that you only print elements in the list occuring at odd indices. **hint use the % operator**

<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 Loops

A 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...

  1. Import the random library by using import random.
  2. Use a while loop that will continue to append random numbers to a list until the list length is greater than 10
    1. Create an empty list
    2. Create a bool variable and set it to True
    3. Establish a while with your boolean condition.
    4. Generate a random number between 0 and 100 and store it to a variable.
    5. Append the number to your list.
    6. Create a condtional statement using if to check the list length. If it's >= 10 set your continue variable to False.
    7. Print your list after each append opeartion.
    8. **what happens if you check your list length before appending the variable.

<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!



Challenge

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:

  1. Create function called targetCounter that takes a list and number as arguments
  2. Create a variable inside the function that will count the number of times a target occurs.
  3. Loop through the list using a simple for loop.
    1. Inside this loop check if the current number is equal to the target using an if conditional statement
    2. if the above condition is satisfied increment the counter using one of two methods
      1. incrementing the counter variable using counter += 1
      2. incrementing the counter using counter = counter + 1

click here for solution (after you've at least given it the old "college try"...


Working with a CSV

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.

  1. First we need the bounding box, which has already been defined for you.
  2. Next create an empty list variable that will have name/location data appended to it when iterating through the CSV
  3. We will open the CSV file here is where some new syntax is going to be helpful.
    1. Let's look at the with open("file name in quotes", "r") as f:
      1. Using the 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.
      2. open() as the name implies, opens the file, and the as f: assigns that open file to a variable.
  4. Next we'll create "reader object" that will actually read in the csv data we've opened. This easily accomplished by assigning it to variable reader = csv.reader(f) (with f being the open csv file)
  5. We'll want to skip the header row since it doesn't contain any data. For now, the easiest way to do this is use the next(reader, None). It will skip the first row.
  6. Using a for loop we'll iterate through all the rows in the reader object and look for locations within the North American bounding box.
    1. create lat, and lon variables assigned to the appropriate index in the row and convert them to a float
    2. Chain comparisons together to evaulate if the lat and lon are within the bounding box. This can be done in one single if statment...
    3. In the event the 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.

Here's a link to the code on repl.it to get you going.

<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)



Week 3:

Working with 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.

Review

  1. Start by creating a function that takes input from the user.
    1. Assume the user follows instructions and enters a number.
    2. Convert it to an integer using int. Just encase they entered a decimal for some reason.
    3. print a string for the if and else function respectively
    4. Create a list of numbers 1-10 inside the function.
    5. Change the raw_input statement to something like "I'm thinking of a number between 1 and 10 (inclusive)". Guess a number.
    6. Use the random library to randomly select an element from the list.
    7. If the user guesses the number correctly, print a "Lucky Guess" statement. If incorrect, 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()


Building a Better Number Guesser

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.

  1. We'll need a variable to count/track the number of guesses. Let's call it counter.
  2. we'll use a while loop so the function will continue to ask for a guess from the user so long as our counter < 3
  3. After each guess we'll check if the guess is the number, if not we'll increment our counter.

Higher or Lower?

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

  1. We'll add the the current if statement in the function you've built thus far. But, we'll re-arrange the order of the if conditions.
  2. Change the first if to anelif
  3. Create 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**.
  4. Add an elif to check if the guess is less than the number and if the counter < 3. If so, print "Guess too low, you did!"

More Guesses?

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..

  1. Inside the final else statment add another raw_input statement asking the user if they would like more guesses.
  2. check the response. If the user answered 'y' reset the counter. if not, then close the game.

<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()


Final Challenge

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)

  1. Define a function named magicBall
  2. Inside the function prompt the user to type a question and store it to a variable name
  3. create an answerList with the following responses:
    1. It is certain
    2. Without a doubt
    3. Yes definitely
    4. As I see it, yes
    5. Most Likely
    6. Outlook good
    7. Yes
    8. Reply Hazy try again
    9. Ask again later
    10. Cannot predict now
    11. Don't count on it
    12. My sources say no
    13. Outlook not so good
    14. Very doubtful
  4. Randomly select an answer from the list using the 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



Week 4: ArcPy

Working with 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.

Create Random Points

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

  1. Pull the Iowa Boundary into ArcMap.
  2. Open the python window in ArcMap.
  3. Create a random set of 100 points inside the the state boundary using the tool.
  4. Go into geoprocessing history and copy the result as a python snippet and paste it into your Python window in Arcmap. Take a look at the snippet for reference.
  5. Now replicate the same process in Python.
  6. ]
  7. Create some variables for the output path, name, number of points to generate, etc.
  8. Any optional parameter can be skipped by just using a comma.
  9. There's an optional parameter after the "MULTIPOINT" parameter, but you can just close the parenthesis to run the tool.

<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")


    

Create a Random Number in a Field

This can be done in the "table view", but it can also be done in the python window...

  1. In the Python window create a field in the newly created randon points. "InTable will be the random points layer, and "FieldName" will be a field you name (i.e. BufferDistance)
  2. We'll actually want this field to be text so we can use it in buffer creation in the next step.
  3. In the field calculator for that field we'll use a simple python function to create a randon number and return it as a string with " MILES" attached to it.
  4. Open the field calculator in the table view
  5. Select the Python button

<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


    

Create a Buffer Around Each Point Based on Randon Number Field

We'll use python in the field calculator to create a random integer between 5 and 25 in a field

  1. In the Python Window create a variables for the output name and distnace field (the field you created for the randon numbers).
  2. Run the Buffer tool to create buffers around each point bassed on the buffer 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")