[英]Python function definition global parameter
Can someone explain why the gloabl variable x & y are not recognized in printfunc, 有人可以解释为什么在printfunc中无法识别gloabl变量x和y,
code.py code.py
global x
global y
def test(val_x=None,val_y=None)
x = val_x
y = val_y
printfunc()
def printfunc():
print('x',x)
print('y',y)
if __name__ = '__main__':
test(val_x=1,val_y=2)
place the global
inside test()
. 放置
global
内部test()
。
global
is used inside functions so that we can change global variables or create variables that are added to the global namespace. global
在函数内部使用,以便我们可以更改全局变量或创建添加到全局命名空间的变量。 : :
def test(val_x=None,val_y=None):
global x
global y
x = val_x
y = val_y
printfunc()
The global
keyword is used inside code block to specify, that declared variables are global, not local. 在代码块内部使用
global
关键字来指定,声明的变量是全局的,而不是本地的。 So move global
inside your functions 所以在你的职能
global
内global
def test(val_x=None,val_y=None): #you also forgot ':' here
global x, y
x = val_x
y = val_y
printfunc()
def printfunc():
global x, y
print('x',x)
print('y',y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.