Python Language Lesson: local and global variables
By default, variables that are introduced in functions have only alimited lifetime and visibility. They are visible only in the function in
which they were created and they disappear when execution returns
from the function.
In the variable y is local to the function first
function(). You cannot use it outside this function. In contrast,
keyword global declares that the variable x belongs to the global
scope, which covers all functions within a module. For this reason, you
can use x also in the function second function(). If a variable
is defined outside any function, it belongs automatically to the global
scope, such as the variable z.
A good rule of thumb is that if the same variable must be used in
more than one function, it must be declared as global or it must be
passed as a parameter to the functions.
Note that you have to assign a value to a variable before it can
be used. It is meaningless to refer to a variable which does not
have any content. Thus, in the example above you must call the
function first function() before calling second function()
or Python will complain NameError: global variable "x"is
not defined. This error means that no value has been assigned to
the variable yet or it was not declared as global.
No comments:
Post a Comment