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
# Python global variable
# Probably should not use this, just pass in arguments
x = 0 # variable is in outer scope
print(x) # prints x (0)
def use_global_variables():
# if using a global variable, the variable will not need to be mention while calling the function
global x # calling the x variable from a function
x += 1
print(x) # prints x after adding one in the function (1)
use_global_variables
=============================================
# Output:
0
1
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
#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)