0

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)
0

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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)

2 Comments

global should not be needed in printfunc(), as they are not assigned there.
They are not necessary, but if you write this, you can easily see, that these variables are global

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.