I am trying to execute this code,

import osgeo.ogr

def findPoints(geometry, results):
    for i in range(geometry.GetPointCount()):
        x,y,z = geometry.GetPoint(i)
    if results['north'] == None or results['north'][1] < y:
        results['north'] = (x,y)
    if results['south'] == None or results['south'][1] > y:
        results['south'] = (x,y)
    for i in range(geometry.GetGeometryCount()):
        findPoints(geometry.GetGeometryRef(i), results)

shapefile = osgeo.ogr.Open("../../Data/tl_2009_us_state/tl_2009_us_state.shp")
layer = shapefile.GetLayer(0)
feature = layer.GetFeature(53)
geometry = feature.GetGeometryRef()

results = {'north' : None,
           'south' : None}

findPoints(geometry, results)

and I am constantly receiving this error,

Traceback (most recent call last):
  File "identify_northsouth_point.py", line 22, in <module>
    findPoints(geometry, results)
  File "identify_northsouth_point.py", line 8, in findPoints
    results['north'] = (x,y)
UnboundLocalError: local variable 'x' referenced before assignment

I have tried global and nonlocal, but it does not work. Since I am not gettin any input from outside the function, so I anyways would not require global or nonlocal.

  • 1
    You might want to make sure you're not shoving an empty geometry object into that function. if the for loop never executes, then yeah, there won't be an x. In fact, are those if statements supposed to be executed in the loop? If so, you need to indent them properly. Otherwise, you're only checking the last point (if there are any). – Lou Apr 30 '12 at 18:01

If you meant to execute the lines following x,y,z = geometry.GetPoint(i) within the for loop, they must be indented an additional 4 spaces. Remember in Python, indentation is part of the syntax.

  • 1
    If you run code in IDLE before hand it will spot indentation and syntax errors and point out where they are. – James Milner Apr 30 '12 at 20:07
  • 1
    In this case it's not a syntax error but a logic error and would not be caught by the IDE. – blah238 Apr 30 '12 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.