Global Keyword in Python

Global keyword is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function.

 It is used to create a global variable and make changes to the variable in a local context. It is not needed for printing and accessing.

Rules of global Keyword

  • If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local. When we define a variable outside of a function, it is global by default. We don't have to use global keyword to define it.
  • We use global keyword to read and write a global variable inside a function
  • There is no need to use global keyword outside a function.

Use of global keyword

Without Global

a = 3
def func_1():
    a = a**5
    print(a)

func_1()  

Output: UnboundLocalError: local variable 'a' referenced before assignment.

This output is an error because we are trying to assign a value to a variable in an outer scope.

With Global

a = 3
def func_1():
    global a
    a = a**5
    print(a)

func_1() 

Output: 243

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

Tags