How to declare a global variable in Python?

PythonServer Side ProgrammingProgramming

What is a global variable?

A global variable is a variable that is declared outside the function but we need to use it inside the function.

Example

 Live Demo

def func():
   print(a)
a=10
func()

Output

10

Here, variable a is global. As it is declared outside the function and can be used inside the function as well. Hence the scope of variable a is global.

We will see what happens if we create a variable of same name as global variable inside the function.

In the above example, the variable a is declared outside the function and hence is global.

If we declare another variable with same name inside the function with some another value. That variable will act as the local variable of the function and its scope will be limited to inside the function. Outside the function, the global variable will hold its original value.

It can be better understood with the help of an example.

Example

 Live Demo

a=10
def func():
   a=5
print("Inside function:",a)
func()
print("Outside function:",a)

Output

Inside function: 5
Outside function: 10

In the above example, a is global variable whose value is 10. Later the func() is called.

Inside func(), another variable a is declared with different value whose scope is only limited to inside the function. Hence, when value of a is printed outside the function later, it carries the same original value as global variable which 10.

The keyword: global

The keyword global is used when you need to declare a global variable inside a function.

The scope of normal variable declared inside the function is only till the end of the function.

However, if you want to use the variable outside of the function as well, use global keyword while declaring the variable.

Understand the difference between both with the help of example implementations.

Example

def func():
   a=5
   print("Inside function:",a)
func()
print("Outside function:",a)

Output

Inside function: 5
Traceback (most recent call last):
print("Outside function:",a)
NameError: name 'a' is not defined

In the above example, the value of a cannot be accessed outside the function, since it is a local variable. Thus, accessing the value of an outside function throws an exception.

Use global keyword

The exception raised in the above example can be resolved if we declare variable a using keyword global.

Example

 Live Demo

def func():
   global a
   a=5
   print("Inside function:",a)
func()
print("Outside function:",a)

Output

Inside function: 5
Outside function: 5

In the above example, the variable a is global and hence its value can be accessed outside the function as well.

raja
Published on 11-Mar-2021 09:05:33
Advertisements