【发布时间】:2021-03-15 02:47:59
【问题描述】:
我的代码
x = 10
def fun():
x = x + 2
print(x)
fun()
print(x)
还有输出错误
UnboundLocalError:赋值前引用了局部变量“x”
【问题讨论】:
标签: python python-3.x debugging error-handling
x = 10
def fun():
x = x + 2
print(x)
fun()
print(x)
UnboundLocalError:赋值前引用了局部变量“x”
【问题讨论】:
标签: python python-3.x debugging error-handling
您尝试在函数fun() 中修改的变量x 是全局范围的。因此,您不能像这样在函数内部访问它。但是,您可以使用:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
附加global x,将允许函数修改全局范围内的变量x。
【讨论】:
您没有将 x 作为函数的参数。这就是为什么。
x = 10
def fun(x):
x = x + 2
print(x)
fun()
print(x)
【讨论】:
您必须在 def fun() 中传递全局 x,因为在 fun() 中没有分配名为 x 的变量。代码如下:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
>>> 12
>>> 12
或
您也可以简单地传递一个参数,但这会影响 x 的值:
x = 10
def fun(x):
x = x + 2
print(x)
fun(x)
print(x)
>>> 12
>>> 10
【讨论】: