Global Variables
A variable created outside any function is called a global variable. All your code can use it, whether inside a function or not.
A variable created inside a function under that same name is a different thing: it is local and exists only for use within that function. The global one keeps its original value and stays untouched.
Use global variable
Here x is defined outside the function and read inside it:
Output: complete Python program
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Local vs global
Here the function creates its own x, sharing a name with the global one:
Output: complete Python program
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
The global Keyword
A variable you create in a function is usually local, so nothing outside that function can use it. The global keyword changes that and lets you create a global variable from inside a function. You also need this keyword when a function has to change an existing global variable.
Create global inside function
With the global keyword, x belongs to the global scope:
Output: complete Python program
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Change global inside function
Inside a function, global lets you give an existing global variable a new value:
Output: complete Python program
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)