如果在给'egg'赋予函数中使用的局部值之前运行print(eggs),为什么会出现错误?

时间:2017-05-24 14:20:54

标签: python python-3.x

我在Python中编写了这段代码,因为我试图理解全局声明 -

eggs=24

def f():
 print(eggs)
 eggs=25
 print(eggs)

f()
print(eggs)

输出应为

24
25
24

Python应该将eggs = 24视为全局变量,并且在调用函数f()时,它应该打印eggs=24,因为到目前为止还没有将本地值分配给egg。然后应将本地值25分配给eggs,并且应在24之后在屏幕上打印25个。函数返回后,应为eggs分配它的全局值24和24应打印最后在屏幕上。

但是我收到一条错误消息“UnboundLocalError: local variable 'eggs' referenced before assignment”。

在理解Python如何运行此函数时我错了?

2 个答案:

答案 0 :(得分:3)

重复(Local variable referenced before assignment in Python?

这应该可以解决问题

eggs = 24

def f():
    global eggs

    print(eggs)
    eggs = 25
    print(eggs)

f()
print(eggs)

Stack Overflow上有很多这样的问题,当你不熟悉Python时,很难理解它在这种特殊情况下的行为,因为在几乎任何命令式语言中,这样的代码都会完全运行



var x = 1;

//prints 1 to console
console.log(x);

function f() {
    x = 2;
}

f();

//prints 2 to console
console.log(x);




但对于Python,您的代码看起来像这样



var x = 1;

console.log(x);

function f() {
    I_AM_NOT_X_EVEN_THOUGH_I_HAVE_A_NAME_X = 2;
}

f();

console.log(x);




答案 1 :(得分:1)

您可以在其他函数中使用全局变量,方法是在分配给它的每个函数中将其声明为全局变量:

eggs=24

def f():
 global eggs
 print(eggs)
 eggs=25
 print(eggs)

def onlyRead():
 print(eggs)

f()
onlyRead()

See reference