How to use a global variable in a Python function?

There are 2 types of variables in Python namely Local variables and Global variables. Local variables mean the variables that are declared inside a function or inside a method whose impact or scope is only present inside that specific block and it doesn't affect the program outside that block.

Global variables mean the variables that are declared outside any function or method and these variables have an impact or scope through the entire program.

We can also instantiate global variables inside a function by using a global keyword, if we want to declare global variables outside a function then we may not need to use a global keyword.

If a variable with the same name globally and locally then inside the function where the local variable is declared the local value is used and the global value is used elsewhere.

Example 1

Let us see an example for a global variable in python −

a = 5 def local(): a = 3 print("Value of local variable a is ",a) local() print("Value of global variable a is ",a)


('Value of local variable a is ', 3)
('Value of global variable a is ', 5)

Example 2

Following is another example for this −

a = 5 def globalV(): print("The value of a is ",a) globalV()


('The value of a is ', 5)

Example 3

In the following example we are defining two global variables after the function −

def product(): return a * b a = 10 b = 5 print(product())



Example 4

Now let us let us try to create a global variable with in a function using the “global” keyword −

def func(): global a a = 7 func() b = 5 add = a + b print(add)



Example 5

Following example shows how the global variable is accessed both inside and outside the function sample.

# This function uses global variable k k = "I like green tea" def sample(): print k #accessing global variable inside function sample() print k #accessing global variable outside function


I like green tea
I like green tea

Start learning Python from here: Python Tutorial

Updated on: 31-Aug-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started