beginner question (True False help)
Joshua Landau
joshua at landau.ws
Fri Aug 9 21:22:01 EDT 2013
On 10 August 2013 00:34, <eschneider92 at comcast.net> wrote:
> What does global mean?
Python has "scopes" for its variables. Most programming languages do.
A "scope" is a restriction on where variables exist -- they exist only
within the scope.
This can be seen in this example:
def function():
# A new "scope" is made when you enter a function
variable = 100
function()
print(variable)
# Error, as variable doesn't exist outside of "function"'s scope
There are lots of different "scopes" in code. Every function has one,
and there are some more too.
One of the scopes is the "global" scope. This is the scope *outside*
of all the functions and other scopes. Everything in the file is
within this sope:
# Make in global scope
variable = 100
def function():
# Works because we're inside the global scope
print(variable)
# Prints "100"
function()
So "a = b" inside the function applies to the function's scope, but
when accessing variables (such as "print(variable)") it will look in
all of the outer scopes too.
If you want to write "a = b" inside the function and change the global
scope, you need to say that "a" refers to the "a" in the global scope.
You do that like this:
def function():
# "variable" is in the global scope, not the functions'
global variable
variable = 100
function()
# Prints "100"
print(variable)
Does that help you understand what "global" means?
More information about the Python-list
mailing list