Current post is on how to access the global variables in Python 3.2.
Global variables can be easily accessed by using the keyword global.
According to Python 3.2 documentation:
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.
Example 1: Change the global variable
globalVariable = False
def ChangeGlobalFunction():
"""Function that changes global variable"""
global globalVariable #Global statement
globalVariable = True
def PrintGlobalFunction():
"""Function that prints global variable"""
print(globalVariable)
PrintGlobalFunction()
ChangeGlobalFunction()
PrintGlobalFunction()
Output:False
True
No comments:
Post a Comment