在 python 上赋值之前引用的局部变量 'nheigth'

local variable 'nheigth' referenced before assignment on python

我是运行以下python函数:

def imageprepare(argv):

    im = Image.open(argv).convert('L')
    width = float(im.size[0])
    height = float(im.size[1])
    newImage = Image.new('L', (28, 28), (255)) 

    if width > height: 
        nheight = int(round((20.0/width*height),0))
        if (nheigth == 0):
            nheigth = 1  
        img = im.resize((20,nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wtop = int(round(((28 - nheight)/2),0))
        newImage.paste(img, (4, wtop))
    else:
        nwidth = int(round((20.0/height*width),0)) #
        if (nwidth == 0):
            nwidth = 1
        img = im.resize((nwidth,20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wleft = int(round(((28 - nwidth)/2),0))
        newImage.paste(img, (wleft, 4))

    tv = list(newImage.getdata())

    tva = [ (255-x)*1.0/255.0 for x in tv] 
    return tva

报错:

UnboundLocalError: local variable 'nheigth' referenced before assignment.

我运行在conda环境下使用python 3.6.

请帮我解决这个问题。我是 python.

的新手

有一个错字:nheigthnheight

正如@Falko 已经发现的那样,您在声明为 nheight 然后用作 nheigth.

的变量中有错字

Python 由于是动态语言,没有强制声明变量,如果没有合适的工具,这种错误在运行前不容易发现。

我建议您使用适当的 Python IDE,例如 PyCharm,它会在您键入时为您发现这些错误。