Python Global Keyword

Python global keyword; Through this tutorial, i am going to show you what is global keyword in python and how to use it.

Global Keyword in Python

Now i will show you what is the global keyword in Python. What are the rules for writing this and how do you use the global keyword in Python programs.

What is global keyword in python

In Python, it is used to create a global variable. And also you can modify variables outside the current scope.

As you know, you cannot change the value of the global variable inside a function. If you don’t know; read this. But if you use the global keyword, then you can also change the value of the global variable inside the function.

Rules to write a global keyword in python

Following are the rules for writing global keywords in Python:

  1. When writing a variable inside a function. So that is the local variable.
  2. If you define a variable outside the function, it is a global variable. For this you do not need global keywords.
  3. If you want to define a global variable inside the function, then you have to use the global keyword.
  4. Use of global keywords outside a function has no effect

Example 1: Accessing global Variable From Inside a Function

a = 1 # global variable
def myFunc():
    print(a)
myFunc()

First defined a global variable in the program named a. After this assigned = = 1 to this variable.

After this created a function called myFunc (). Inside this function, called the global variable.

After that called this function from which got some output which is given below.

Output

1

Example 2: Modify Global Variable From Inside a Function using global keyword

a = 0 # global variable
def myFunc():
    global a
    a = a + 2 # increment by 2
    print("Inside add():", a)
myFunc()
print("In main:", a)

First defined a global variable in the program named a. After this assigned = = 1 to this variable.

After this created a function called myFunc (). Inside this function and modified the value of the global variable by using the global keyword.

After that called this function from which got some output which is given below.

Output

Inside add(): 2
In main: 2

Note:- If you want to change the value of the global variable inside the function, then you have to use the global keyword for this. you will give an example of changing the value of a global variable.

In this post, you have learned how to change the value of the global variables by using the global keyword.

Recommended Python Tutorials

Recommended:-Python Data Types
Recommended:-Functions in Python

Be First to Comment

Leave a Reply

Your email address will not be published.