0
def foo(x,y):
    global a 
    a=42 
    x,y=y,x 
    b=33 
    b=17 
    c=100 
    print(a,b,x,y) 
    
a,b,x,y=1,15,3,4 

foo(17,4) 
print(a,b,x,y) 
  1. For foo(17,4), does global a means that a is a global variable for the entire program, even outside this funciton? And why does a=1 be modified to 42?
  2. For print(a,b,x,y), it doesn't call the function, so it should just prints global variables(defined outside the function), but why a is also changed to 42?
ANEN
  • 11
  • 1
  • 1
    "does global a means that a is a global variable for the entire program, even outside this funciton? " no, that isn't what it means at all. It means that `a` is referring to the global variable **inside `foo`** and you only need to use `global a` because you *assign to `a`*. – juanpa.arrivillaga Nov 07 '22 at 19:43
  • 2) because **you call the function** before that line? Why did you *expect* that function call not to do anything? – juanpa.arrivillaga Nov 07 '22 at 19:43
  • See [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – craigb Nov 07 '22 at 19:44
  • _why a is also changed to 42_ Because you called the function `foo()`, and inside that function is the line of code `a=42`. – John Gordon Nov 07 '22 at 19:57

0 Answers0