xxxxxxxxxx
#A global variable can be accessed from any function or method.
#However, we must declare that we are using the global version and not the local one.
#To do this, at the start of your function/method write "global" and then the name of the variable.
#Example:
myVariable = 1
def myFunction():
global myVariable
print(myVariable)
myFunction()
xxxxxxxxxx
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
xxxxxxxxxx
x = 5 #Any variable outside a function is already a global variable
def GLOBAL():
global y #if a variable is inside a function, use the 'global' keyword to make it a global variable
y = 10 # now this variable (y) is global
xxxxxxxxxx
#A global variable can be accessed from the hole program.
global var = "Text"
xxxxxxxxxx
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
xxxxxxxxxx
def my_function():
global my_variable
my_variable = 10
my_function()
print(my_variable) # Output: 10
xxxxxxxxxx
def my_function():
global global_variable
global_variable = 10
def another_function():
print(global_variable)
# Updating the global variable
my_function()
# Accessing the global variable
another_function()
xxxxxxxxxx
#### A_FILE.PY
a_global_variable = "Hello"
####sys.path.append(".")
##### B_FILE.PY
import a_file
output = a_file.a_global_variable
print(output)
------> Hello