xxxxxxxxxx
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
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
globalvar = "flower"
def editglobalvar():
global globalvar # accesses the "globalvar" variable, so when we change it
# it won't assign the new value to a local variable,
# not changing the value of the global variable
globalvar = "good" # assigning new value
print(globalvar) # outputs "flower"
# if we didnt use the "global" keyword in the function, it would print out
# "flower"
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
def my_function():
global my_variable
my_variable = 10
my_function()
print(my_variable) # Output: 10
xxxxxxxxxx
#A global variable can be accessed from the hole program.
global var = "Text"
xxxxxxxxxx
x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
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()