How To Use Global Variables in Functions
Forget scope, let’s go global
Global variables are variables that are accessible regardless of scope. Traditionally, functions operate within a local scope with limited access to variables that are not passed as a parameter. Setting a variable as global breaks the rules of encapsulation so that the specified variable is more accessible.
Variables Are Available Inside Functions
In Python, variables are accessible within a function. This can be shown in the snippet below, where no values are passed as parameters but the variables a and b are able to be printed.def myFunction():
print(a,b)a = "Terra"
b = "Branford"myFunction() # Terra Branford
print(a,b) # Terra Branford
Modifications Are Local in Scope
These values are able to be edited as well; however, changes made in the local environment are lost once the execution of the function completes. In the snippet below, the variable values are changed and printed, and they are unaffected when printed outside of the function.def myFunction():
a = "Celes"
b = "Chere"
print(a,b)a = "Terra"
b = "Branford"myFunction() # Celes Chere
print(a,b) # Terra Branford
Using the “global” Keyword
To globalize a variable, use the global keyword within a function’s definition. Now changes to the variable value will be preserved. In the snippet below, a is globalized and b is not. Subsequently, the change to a is kept, while b remains as the original value prior to the function’s execution.def myFunction():
global a
a = "Celes"
b = "Chere"
print(a,b)a = "Terra"
b = "Branford"myFunction() # Celes Chere
print(a,b) # Celes Branford