Can someone explain why the gloabl variable x & y are not recognized in printfunc,
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
is used inside functions so that we can change global variables or create variables that are added to the global namespace. :
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. So move global
inside your functions
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.