Try this out:
A = 1
B = 2
C = A + B
def main():
global C
print A
The output of main() is 1.
Why is this? Why should main get to know about the other global variables used to evaluate C?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Global variables are always available to all local scopes in Python, including functions. In this case, within
main()A,B, andCare all in scope.The
globalkeyword doesn’t do what it seems you think it does; rather, it permits a local scope to manipulate a global function (it makes global variables “writable”, so to speak). Consider these examples:Here, the output will be
Now, consider this:
In this case, the output will be
In the first case,
c = 3merely shadowscuntil its scope is up (i.e. when the function definition ends). In the second case, we’re actually referring to a reference to a globalcafter we writeglobal c, so changing the value ofcwill lead to a permanent change.