Global and Local Variables
Global and Local Variables
VARIABLES
GLOBAL
Global variables are the one that is defined and declared outside a function and we
need to use them inside a function.
GLOBAL VARIABLES
Variables that are created outside of a function are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
THE GLOBAL KEYWORD
Normally, when you create a variable inside a function, that variable is local, and can
only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)