python-3.xarcpywing-ide

Variable Initialization with Methods (Python)


Is there a reason my count equals zero, when it should be 29. I tried to initialize count inside my function but then it says its not defined.

shapefile = "Schools.shp"
work = r"c:\Scripts\Lab 6 Data"
facility = "HIGH SCHOOL"
count = 0

def numSchools(work, shapefile, facility):

    whereClause = "\"FACILITY\" = 'HIGH SCHOOL' " # where clause for high schools
    cursor = arcpy.SearchCursor("Schools.shp", facility)
    result = arcpy.GetCount_management(cursor)
    for result in cursor:
        count = int(result.getOutput(0))# Get the first value from the Result object
    return count

print ("The number of " + facility + " are:"), int(count) 

In its most basic form, this code returns the correct number of schools.

import arcpy

arcpy.env.workspace = r"c:\Scripts\Lab 6 Data"
result = arcpy.GetCount_management("Schools.shp")
count = int(result.getOutput(0)) 
print ("The number of rows in 'schools' is "),int(count)

However, Schools.shp is a file that contains 201 schools.

I need to go within that file to a field called 'facilities', then within that a get the number of 'high schools' (I know how to do this part). BUT I also need this code to work as a function (Which is what I am having trouble with).


Solution

  •             searchCurs = arcpy.da.SearchCursor(shapefile, field, whereClause)
                row = searchCurs.next()
                for row in searchCurs:
                                value = row[0]
                                high_schools = [row[0] for row in arcpy.da.SearchCursor(shapefile, field, whereClause)]
                                count = len(high_schools)
                                print count