0

This function shows that the value of variable "a" inside the function is influenced by the value of "a" in the global environment

a=1

def f(x):
    print(a)
    return x+a

f(3)

The output that I get is 4 and the printed value of a is 1. From my understanding of functions in python, the global environment is separate from the local environment (inside the function), so I cannot explain why the value of a is 1 inside the function. Could somebody please explain. Much appreciated.

PS: this is my very first post on Stack overflow, so please excuse my style of asking if it's not to your liking.

  • 3
    You can read global variables from functions, assuming they aren't masked by local variables of the same name. If you wish to write global variables from a function, however, then you have to explicitly declare them `global`. – Tom Karzes Jan 27 '16 at 11:21
  • The answers [here](http://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) may help. – PM 2Ring Jan 27 '16 at 11:26

0 Answers0