UnboundLocalError:赋值之前引用了局部变量“ x”

Sam*_*007 4 python gdal

我正在尝试执行此代码,

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)
Run Code Online (Sandbox Code Playgroud)

而且我不断收到此错误,

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
Run Code Online (Sandbox Code Playgroud)

我尝试了全局和非本地,但是它不起作用。由于我没有从函数外部获取任何输入,因此无论如何我都不需要全局或非本地。

kin*_*all 5

错误消息指出该变量x没有值。由于(在重复中)分配了for循环,因此这意味着for循环甚至不会执行一次。而且唯一可能发生的方法就是geometry.GetPointCount()返回0。因此,这是必须发生的事情。添加print geometry.GetPointCount()确认。

您是否打算将if语句放在循环内,以便对几何中的每个点执行这些语句,而当几何有0个点时根本不执行这些语句?如果是这样,请正确缩进。