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

Python for循环中'yen'未定义错误的原因及解决方法

问题分析与解决办法

嘿,这个错误其实很好排查——就是变量名不匹配搞的鬼!

先看你贴的代码片段:

width, height = 240, 60 
midx, midy = width // 2, height // 2 
for xen in range(width): 
    for 褍en in range(height):  # 注意这里的变量名是「褍en」,不是yen!
        if xen < 5 or xen >= width - 5 or 褍en < 5 or 褍en >= height - 5: 
            image[xen, yen] = border_color  # 但这里你写的是yen
        elif midx - 20 < xen < midx + 20 and midy - 20 < 褍en < midy + 20: 
            image[xen, yen] = square_color  # 这里也是yen

你第二个for循环里定义的变量是褍en(这个字符看起来是印刷/编码错误导致的乱码生僻字),但后面赋值的时候用的是yen——Python对变量名是严格匹配的,大小写、字符一个都不能错,所以它找不到yen这个变量,自然就抛出NameError了。

修正方法

直接把变量名统一就行,推荐把乱码的褍en改成正常的yen,毕竟yen是符合命名习惯的英文变量名,乱码字符大概率是旧书印刷失误。

修正后的代码如下:

width, height = 240, 60 
midx, midy = width // 2, height // 2 
for xen in range(width): 
    for yen in range(height): 
        if xen < 5 or xen >= width - 5 or yen < 5 or yen >= height - 5: 
            image[xen, yen] = border_color 
        elif midx - 20 < xen < midx + 20 and midy - 20 < yen < midy + 20: 
            image[xen, yen] = square_color 

小提醒

旧书因为年代久远,印刷技术或者后续数字化转码时很容易出现字符乱码的问题,以后遇到类似的变量未定义错误,先仔细核对变量名的每个字符,尤其是看起来奇怪的生僻字,十有八九是印刷/转码错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:40:19