WhatsApp and Telegram Group Card
WhatsApp Group Join Now
Telegram Group Join Now

Global Keyword in Python

In this example of Global keyword of python, we will see what is Global Keyword in Python with help of we will understand the basic phenomena of Global Keyword. So lets get started,

As we know, Global variable means that is accessible within the function as well as outside the function also.

Before going to know about the Global keyword, first we have to understand scope of the variable with an example. For Example :-

# global variable
num = 1 

def add():
    print(num)

add() #function call

Output

1

Explanation :- In this example, we can see that we have accessed a global variable from inside of a function without using Global Keyword, means we can access the variable but we can not modify as we have mentioned in the below example.

Example 2

# global variable
num = 1 

def add():

     # increment c by 2
    num = num + 2

    print(num)

add()

Output

UnboundLocalError: local variable 'num' referenced before assignment

Ex :- Modifying Global Variable From Inside a Function using global Keyword

# global variable
num = 1 

def add():

    # use of global keyword
    global num

    # increment c by 2
    num = num + 2 

    print("num = ", +num)

add()

Output :-

num = 3

In the above example, we have defined num as theglobal keyword insideadd()function.

Then, we have incremented the variable num by 2, i.e., num = num + 2.

Hope, after going through the whole article, all your doubts are cleared related to Global Keyword in Python.

Kindly, visit the Python for more.

In case of any query, Please feel free to contact us.

Kindly share it with your friends.

Regards, EduPaat Team