Python Local vs Global Variables


Introduction

While working with functions, it is very much important to know about the scope of the variable.

In python, we have two types of variables

  1. Local Variables
  2. Global Variables

Local Variable

A variable that is declared inside the function is known as the local variable. Local variables can only be accessed from inside the function. We get the name error, if we try to access the local variable from outside the function.

In [1]:
def details():
    #local variable
    name = "Steve"
    print("Name :", name)
    
def more_details():
    print("Name :", name)

It works, as the variable name is defined in details function.

In [2]:
details()
Name : Steve

It fails, as the variable name is local to details function and cannot be used outside that.

In [3]:
more_details()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-dfa6984d933c> in <module>
----> 1 more_details()

<ipython-input-1-5e448cc2db6b> in more_details()
      5 
      6 def more_details():
----> 7     print("Name :", name)

NameError: name 'name' is not defined

Global Variable

A variable that is declared outside the function is known as the global variable. Global variables can be accessed throughout the program by all the functions.

In [1]:
#global variable
name = "John"
def details():
    #local variable
    name = "Steve"
    print("Name :", name)
    
def more_details():
    print("Name :", name)

It prints “Steve”, because we are locally overwriting name with “Steve”.

In [2]:
details()
Name : Steve

As “name” variable is globally defined, so it works.

In [3]:
more_details()
Name : John