在python中访问函数中的全局变量

时间:2018-01-22 19:17:39

标签: python-3.x global-variables local-variables

我有两段代码:

def g(y):
  print(x)
x = 5 
g(x)

def h(y):
  x = x + 1
x = 5
h(x)

第一段代码完美地打印'5',而第二段则返回:

UnboundLocalError: local variable 'x' referenced before assignment

这究竟意味着什么?是否试图说它在评估行x = x + 1之前尝试评估行x=5?如果是这样,为什么第一段代码没有产生任何错误?它同样必须在为print(x)分配值之前评估行x

我想我可能会误解如何调用函数。但我不知道我错了什么。

2 个答案:

答案 0 :(得分:0)

# first block: read of global variable. 
def g(y):
  print(x)
x = 5 
g(x)

# second block: create new variable `x` (not global) and trying to assign new value to it based on on this new var that is not yet initialized.
def h(y):
  x = x + 1
x = 5
h(x)

如果您想使用全局,则需要使用global关键字明确指定:

def h(y):
  global x
  x = x + 1
x = 5
h(x)

答案 1 :(得分:0)

正如Aiven所说,或者您可以像这样修改代码:

def h(y):
   x = 9
   x = x + 1
   print(x) #local x
x = 5
h(x)
print(x) #global x