Global keyword in Python

PythonServer Side ProgrammingProgramming

Different variables in a python program have different scope. Depending on where it is declared, the variable may or may not be accessible inside a function. Sometimes we will need to modify a variable that is present inside a function from outside its current scope. In such a scenario we use the global keyword with the variable name.

Following are the key points about the global keyword

  • A variable declared outside a function is a global variable by default.

  • We use a global keyword for a variable which is inside a function so that it can be modified.

  • Without the global keyword, the variable inside a function is local by default.

Without Global

In the below examples we will see how the variable change happens without a global keyword. This will help us understand, what difference the global keyword makes in the next program. In the below example we try to modify the global variable inside the function. But an error occurs as we can not modify a global variable inside a function.

Example

 Live Demo

var = 321
# function to modify the variable
def modify():
   var = var * 2
   print(var)
# calling the function
modify()

Output

Running the above code gives us the following result −

UnboundLocalError: local variable 'var' referenced before assignment

With Global

Now we declare the variable inside the function along with the keyword global. This makes the variable modifiable.

Example

 Live Demo

var = 321
# function to modify the variable
def modify():
   global var
   var = var * 2
   print(var)
# calling the function
modify()

Output

Running the above code gives us the following result −

642

Global within Nested Functions

If we have to use nested functions then we have to declare the global keyword in the inner function so that the variable can be modified.

Example

def outer_func():
   var = 321
# function to modify the variable
   def modify():
      global var
   var = var * 2
   print(var)
# calling the function
   modify()
outer_func()

Output

Running the above code gives us the following result −

642
raja
Updated on 17-Oct-2019 12:58:23

Advertisements