1#A global variable can be accessed from the hole program.
2
3global var = "Text"
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#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()
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
1def Takenin():
2 global ans
3 ans = "This is the coorect way to do it"
4
5def Return():
6 Takenin()
7 print(f"ans :{ans}")