Below is one possible solution to Practice Exercise B with comments to explain what is going on. If you find a more efficient way to code a solution, please share it through the discussion forums.
# This script determines the percentage of cities with two park # and ride facilities import arcpy arcpy.env.overwriteOutput = True cityBoundaries = "D:\\Data\\Geog485\\Lesson3PracticeExerciseB\\Washington.gdb\\CityBoundaries" parkAndRide = "D:\\Data\\Geog485\\Lesson3PracticeExerciseB\\Washington.gdb\\ParkAndRide" parkAndRideField = "HasTwoParkAndRides" cityIDStringField = "CI_FIPS" citiesWithTwoParkAndRides = 0 numCities = 0 # Make a feature layer of all the park and ride facilities arcpy.MakeFeatureLayer_management(parkAndRide, "ParkAndRideLayer") # Make an update cursor and loop through each city with arcpy.da.UpdateCursor(cityBoundaries, (cityIDStringField, parkAndRideField)) as cityRows: for city in cityRows: # Create a query string for the current city cityIDString = city queryString = '"' + cityIDStringField + '" = ' + "'" + cityIDString + "'" # Make a feature layer of just the current city polygon arcpy.MakeFeatureLayer_management(cityBoundaries, "CurrentCityLayer", queryString) try: # Narrow down the park and ride layer by selecting only the park and rides # in the current city arcpy.SelectLayerByLocation_management("ParkAndRideLayer", "CONTAINED_BY", "CurrentCityLayer") # Count the number of park and ride facilities selected selectedParkAndRideCount = arcpy.GetCount_management("ParkAndRideLayer") numSelectedParkAndRide = int(selectedParkAndRideCount.getOutput(0)) # If more the one park and ride found, update the row to TRUE if numSelectedParkAndRide >= 2: city = "TRUE" # Don't forget to call UpdateRow cityRows.updateRow(city) # Add 1 to your tally of cities with two park and rides citiesWithTwoParkAndRides += 1 finally: # Delete current cities layer to prepare for next run of loop arcpy.Delete_management("CurrentCityLayer") numCities +=1 # Clean up park and ride feature layer arcpy.Delete_management("ParkAndRideLayer") # Calculate and report the number of cities with two park and rides if numCities <> 0: percentCitiesWithParkAndRide = ((1.0 * citiesWithTwoParkAndRides) / numCities) * 100 else: print "Error with input dataset. No cities found." print str(percentCitiesWithParkAndRide) + " percent of cities have two park and rides."
The video below offers some line-by-line commentary on the structure of the above solution: