1#A global variable can be accessed from the hole program.
2
3global var = "Text"
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
1a = 'this is a global variable'
2def yourFunction(arg):
3 #you need to declare a global variable, otherwise an error
4 global a
5 return a.split(' ')
6
1#### A_FILE.PY
2a_global_variable = "Hello"
3####sys.path.append(".")
4
5##### B_FILE.PY
6import a_file
7
8output = a_file.a_global_variable
9
10print(output)
11------> Hello
1#A global variable can be accessed from any function or method.
2#However, we must declare that we are using the global version and not the local one.
3#To do this, at the start of your function/method write "global" and then the name of the variable.
4#Example:
5myVariable = 1
6
7def myFunction():
8 global myVariable
9 print(myVariable)
10
11myFunction()