Python Variable Types


Local Variable

Local variables are the variables that declared inside the function and have scope within the function.

Example: 

#Local Variables:
print("============================")

print("Local Variables:")

# Declaring a function
def add():  
    # Defining local variables. They has scope only within a function  
    a = 20  
    b = 30  
    c = a + b  
    print("The sum is:", c)

# Calling a function  
add()



OUTPUT:

Local Variables:
The sum is: 50

Note:
If you are given,
add()
print(a)
it will give error:  The sum is: 50
   print(a)
   NameError: name 'a' is not defined


=============================================================================================


Global Variables

Global variables can be used throughout the program, and its scope is in the entire program. We can use global variables inside or outside the function.


#Global Variables:
print("============================")

print("Global Variables:")

# Declare a variable and initialize it  
x = 101  
  
# Global variable in function  
def mainFunction():  
    # printing a global variable  
    global x  
    print(x)  

    # modifying a global variable  
    x = 'Welcome To Javatpoint'  
    print(x)  
  
mainFunction()  
print(x) 


OUTPUT:

Global Variables:
101
Welcome To Javatpoint
Welcome To Javatpoint