Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 "", line 22, in <module>
    findPoints(geometry, results)
  File "", 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.

share|improve this question
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
up vote 1 down vote accepted

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.

share|improve this answer
Thanks my indentation was incorrect – Sam007 Apr 30 '12 at 18:30
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
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 posting your answer, you agree to the privacy policy and terms of service.

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