What is a global statement? And how is it used? I have read Python’s official definition;
however, it doesn’t make a lot of sense to me.
What is a global statement ? And how is it used? I have read
Share
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.
Every "variable" in python is limited to a certain scope. The scope of a python "file" is the module-scope. Consider the following:
Objects with local scope die as soon as the function exits and can never be retrieved (unless you
returnthem), but within a function, you can access variables in the module level scope (or any containing scope):However, you can’t use assignment on that reference and expect that it will be propagated to an outer scope:
Now, we’re finally to
global. Theglobalkeyword is the way that you tell python that a particular variable in your function is defined at the global (module-level) scope.In other words, you can change the value of
myvariablein the module-scope from withinfuncif you use theglobalkeyword.As an aside, scopes can be nested arbitrarily deeply:
Now in this case, none of the variables are declared at the global scope, and in python2, there is no (easy/clean) way to change the value of
xin the scope offunc1from withinfunc3. That’s why thenonlocalkeyword was introduced in python3.x .nonlocalis an extension ofglobalthat allows you to modify a variable that you picked up from another scope in whatever scope it was pulled from.