Python 全局变量/范围混淆 [英] Python global variable/scope confusion
问题描述
我已经开始自学 Python,并且注意到全局变量和作用域有些奇怪.当我运行这个:
I've started teaching myself python, and have noticed something strange to do with global variables and scope. When I run this:
x = 2
y = 3
z=17
def add_nums():
y = 6
return z+y
打印出23的结果...但是,当我将回报扩大为:
The result of 23 is printed... However, when I expand the return to be:
x = 2
y = 3
z=17
def add_nums():
y = 6
z = z + y
return z
我在第 6 行收到以下错误:
I get the following error on line 6:
Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the
method or variable before you try to use it.
<小时>
我很困惑为什么我在这里收到错误,因为 z 是全局可访问的.
I'm confused as why I am getting an error here, as z is global an accessible.
推荐答案
当一个变量在等号的左边时,python 会创建一个局部变量.当变量位于等号的右侧时,python 将尝试查找局部变量,如果找不到,它将使用全局变量.在您的示例中, z 位于等号的右侧和左侧,以避免歧义 python 引发错误.您需要使用 global
语法来避免这种情况:
When a variable is on the left side of an equal sign python will create a local variable. When the variable is on the right side of the equal sign python will try to look for a local variable and if he can't find one then it will use a global variable. In your example, z is on the right and left side of the equal sign, to avoid ambiguities python raises an error. You need to use the global
syntax to avoid this:
x = 2
y = 3
z=17
def add_nums():
global z
y = 6
z = z + y
return z
这篇关于Python 全局变量/范围混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!