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

为什么Python在函数内修改外部变量时会判定为创建新局部变量?

问题根源

Python默认的变量作用域规则如下:

  • 如果函数内部仅读取某个变量,优先读取全局作用域的同名变量
  • 如果函数内部对某个变量执行赋值操作,Python会自动将该变量识别为局部变量,不会使用全局同名变量,这就是你遇到的无法识别外部fill、empty变量的原因

你修改后的代码仍然无效,是因为calculate返回的fill、empty没有被接收赋值给全局变量,render_function读取的还是初始的空字符串。

解决方案

方案一:传参+返回值(更推荐,逻辑更易维护)

完全规避全局变量依赖,代码逻辑更清晰:

import time
import os

position = [0, 1, 0]
isRunning = True

def calculate():
    empty = ""
    fill = ""
    for x in position:
        render_val = x
        if render_val == 0:
            empty = "-"
        if render_val == 1:
            fill = "⬛"
    return fill, empty

def render_function(fill, empty):
    if position[0] == 1:
        print(fill, empty)
    if position[0] == 0:
        print(empty, fill)

os.system('clear')
while isRunning:
    # 接收calculate返回的计算结果
    fill, empty = calculate()
    # 将结果传入渲染函数
    render_function(fill, empty)
    time.sleep(3)
    os.system('clear')

方案二:global声明(适合快速修改现有代码)

如果不想大幅调整现有逻辑,可以在函数内声明要使用全局变量:

import time
import os

ant = "#"
position = [0, 1, 0]
render = 0
isRunning = True
fill = ""
empty = ""

def calculate():
    # 声明以下变量使用全局作用域的同名变量
    global empty, fill, render
    for x in position:
        render = x
        if render == 0:
            empty = "-"
        if render == 1:
            fill = "⬛"

def render_function():
    if position[0] == 1:
        print(fill, empty)
    if position[0] == 0:
        print(empty, fill)

os.system('clear')
while isRunning:
    calculate()
    render_function()
    time.sleep(3)
    os.system('clear')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:54:03