python中的全局和局部范围 [英] Global and local scope in python
本文介绍了python中的全局和局部范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于python中局部和全局作用域的初学者问题
Just a beginner question about local and global scope in python
X = 100
#is X a global variable?.We defined it outside the function scope
def foo():
print(X)
return X
#it prints 100 and even returns it
def foo():
X = X + 10
#local error
#UnboundLocalError: local variable 'X' referenced before assignment
def foo():
global X
# if X is a global variable why specify again?
X = X + 10
return X
推荐答案
要修改变量的全局副本,您需要使用 global
关键字,但不需要 global
如果你只是访问那个.
To modify global copy of a variable you need the to use the global
keyword, but you don't need global
if you are only accessing that.
这篇关于python中的全局和局部范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文