Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

share|improve this question
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
add comment

1 Answer

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
1  
Thanks my indentation was incorrect –  Sam007 Apr 30 '12 at 18:30
1  
If you run code in IDLE before hand it will spot indentation and syntax errors and point out where they are. –  Loxodrome 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
add comment

Your Answer

 
discard

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.