OneCompiler

Understanding Global Keyword in Python

299


In this post, we will learn about the global keyword in Python.

What is the use of global keyword?

It is used to modify the global variabes inside a function.

Scope of a variable

Before you start learning about the global keyword, you need to understand the scope of a variable.

  • Scope indicates the range upto which a variable can be accessed
  • A variable declared outside of a function has a global scope
  • A variable declared inside of a function will have a local scope

Usage of global keyword

Consider the below example,

# Global variable
a = 10

def display (): 
  print (a)

display()

when the program is executed the output will be

10

Now, let's try to change the value of a inside display()

# Global variable
a = 10

def display (): 
  a = a + 1
  print (a)

display()

You will notice an error like below

UnboundLocalError: local variable 'a' referenced before assignment

Which shows us that we cannot modify a global variable inside a local scope. To do that we need to use the global keyword as below.

# Global variable
a = 10

def display (): 
  global a
  a = a + 1
  print (a)

display()

Check output Here