1trying to assign a global variable in a function will result in the function creating a new variable
2with that name even if theres a global one. ensure to declare a as global in the function before any
3assignment.
4
5a = 7
6def setA(value):
7 global a # declare a to be a global
8 a = value # this sets the global value of a
1"""
2USING GLOBALS ARE A BAD IDEA, THE BEST WAY TO PERFORM AN ACTION WHICH NEEDS GLOBALS WOULD
3BE TO USE RETURN STATEMENTS. GLOBALS SHOULD ONLY EVER BE USED IN RARE OCCASIONS WHEN YOU
4NEED THEM
5"""
6
7# allows you to modify a variable outside its class or function
8
9EXAMPLE:
10
11def test_function():
12 global x
13 x = 10
14
15test_function()
16print(f"x is equal to {x}") # returns x is equal to 10
17
1globvar = 0
2
3def set_globvar_to_one():
4 global globvar # Needed to modify global copy of globvar
5 globvar = 1
6
7def print_globvar():
8 print(globvar) # No need for global declaration to read value of globvar
9
10set_globvar_to_one()
11print_globvar() # Prints 1
1
2x = 5 #Any variable outside a function is already a global variable
3
4def GLOBAL():
5 global y #if a variable is inside a function, use the 'global' keyword to make it a global variable
6 y = 10 # now this variable (y) is global