Python中的全局和局部变量 [英] Global and local variables in Python
问题描述
我正在学习Python。一本关于Python 3的书说以下代码应该可以正常工作:
I am learning Python. A book on Python 3 says the following code should work fine:
def funky():
print(myvar)
myvar = 20
print(myvar)
myvar = 10
funky()
但是当我在Python 3.3中运行它时,我得到了
But when I run it in Python 3.3, I got the
UnboundLocalError: local variable 'myvar' referenced before assignment
错误。我的理解是, funky
中的第一个 print(myvar)
应该是10,因为它是一个全局变量。第二个 print(myvar)
应该是20,因为本地 myvar
被定义为20.这里是怎么回事?请帮助澄清。
error. My understanding is that the first print(myvar)
in funky
should be 10 since it's a global variable. The second print(myvar)
should be 20 since a local myvar
is defined to be 20. What is going on here? Please help clarify.
推荐答案
您需要在函数中调用 global
You need to call global
in your function before assigning a value.
def funky():
global myvar
print(myvar)
myvar = 20
print(myvar)
myvar = 10
funky()
请注意,您可以在不调用全局的情况下打印该值,因为您可以在不使用 global
的情况下访问全局变量,但尝试分配值需要它。
Note that you can print the value without calling global because you can access global variables without using global
, but attempting to assign a value will require it.
这篇关于Python中的全局和局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!