You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错:局部变量'nheigth'未赋值即引用,求排查解决

解决“局部变量'nheigth'未赋值即引用”的报错

嘿,这个问题我一眼就看出来啦——就是个低级拼写错误闹的!你仔细瞅代码里的变量名:

在width > height的分支里,你明明定义的是nheight(正确拼写:n-h-e-i-g-h-t),但后面判断和赋值的时候却写成了nheigth(把g和h的顺序搞反了!)。Python对变量名的拼写、大小写都严格得很,找不到这个拼写错误的变量,自然就抛出“未赋值即引用”的报错啦。

修复后的完整代码

from PIL import Image, ImageFilter

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 (nheight == 0):  # 把错误的nheigth改成正确的nheight
            nheight = 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))
        # 这里如果后续有使用nwidth的代码,记得别犯同样的拼写错误哦
        # 补全你未写完的逻辑即可

核心修正说明

  • 全局替换错误拼写的nheigth为正确的nheight
  • 顺带提醒:在else分支里定义的nwidth,后续使用时也要注意别写错变量名,避免踩同样的坑

内容的提问来源于stack exchange,提问作者sarath menon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:32:58