为什么范围是这样工作的?

2024-04-25 01:57:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题是因为我的一个学生问了一个关于以下代码的问题,我真的完全被难住了。任何帮助都将不胜感激。你知道吗

当我运行此代码时:

#test 2

a = 1

def func2(x):
    x = x + a
    return(x)

print(func2(3))

它工作得很好。它能够获取全局范围内的变量a并使用其值执行计算并返回值4。你知道吗

但是,如果我将其改为:

# test 3

a = 1

def func3(x):
    a = x + a
    return(x)

print(func3(3))

然后我得到一个错误:

local variable 'a' referenced before assignment

为什么只有当我想将函数中a的值更新为基于其原始值的新值时才会出现此错误?我不明白什么?我觉得这第二段代码应该很好用。你知道吗

提前感谢您的帮助和见解。你知道吗


Tags: 代码testreturnlocaldef错误全局variable
2条回答
a = 1

def func3(x):
    global a
    a = x + a
    return(x)

print(func3(3))

现在应该可以了。你知道吗

当您将语句a=x+a放在函数中时,它会创建一个新的局部变量a,并尝试引用它的值(这显然是以前没有定义过的)。因此,您必须在更改全局变量的值之前使用global a,以便它知道引用哪个值。你知道吗

编辑:

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

def func3(x):
    a = x + a
    return(x)

在a=x+a(因此,x+a)的右侧,“x”作为变量传递,其中“a”不作为变量传递,因此是一个错误。 不使用全局变量:

    a = 1

    def func3(x, a=2):
        a = x + a
        return(x)

    func3(3)

回报:5

相关问题 更多 >