[英]function inside a function - global and nonlocal scope
我正在尝试使用全局和非本地范围的以下代码。 以下代码段工作没有任何问题。
def countdown(start):
n = start
def display():
print('--> %d' % n)
def decrement():
nonlocal n ##using python3
n -= 1
while n > 0:
display()
decrement()
countdown(10)
倒计时(10)
但为什么我不能使用全球n? 而不是非本地的。 这给了我
UnboundLocalError: local variable 'n' referenced before assignment
这是片段
def countdown(start):
global n ##defined it global
n = start
def display():
print('--> %d' % n)
def decrement():
##no nonlocal varibale here
n -= 1
while n > 0:
display()
decrement()
倒计时(10)
您需要在使用它的每个函数中将变量标记为全局变量(或者更确切地说,指定给它的每个函数)。 你在countdown
中将n
标记为全局,但是decrement
仍然认为它是本地的。 如果你想decrement
也使用全局n
,你需要在decrement
另一个global n
。
全局声明不会自动应用于嵌套函数。 你需要另一个声明:
def decrement():
global n
n -= 1
所以decrement
n
也指全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.