Skip to main content

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
Submitted by devanshi.srivastava on July 6, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.