xxxxxxxxxx
#A global variable can be accessed from the hole program.
global var = "Text"
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
def my_function():
global my_variable
my_variable = 10
my_function()
print(my_variable) # Output: 10
xxxxxxxxxx
#Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
xxxxxxxxxx
x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
xxxxxxxxxx
def my_function():
global my_variable
my_variable = 10
# Accessing the global variable
print(my_variable)
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()