Python global Keyword



The Python, global keyword allows us to modify the variables which are outside the current scope. It is a case-sensitive keyword. It is used to create a global variable. The variable is declared outside the function or in the global scope is known as global variable.

The global variable cane be accessed inside or outside the function. When we use the global keyword inside the if-else statements, it will result a SyntaxError.

When we create a variable outside the function it is a global variable by default no need to specify the global keyword before it. We use the global keyword to read and write a global variable inside a function.

Usage

Following is the usage of the Python global keyword −

global variable_name

Where, variable_name is the name of the variable which we need to declare global.

Example

Following is an basic example of the Python global keyword −

var1 = 100
print("Variable before function :", var1)
def fun1():
    global var1
    var1 = 879
    print("Variable inside the function :",var1)    
fun1()
print("Variable outside the function :",var1)

Output

Following is the output of the above code −

Variable before function : 100
Variable inside the function : 879
Variable outside the function : 879

Using the global Keyword in Nested Functions

When we defined one function inside another function is known as nested function. We can also use the global keyword inside the nested function.

Example

Here, we have defined the nested function and created global variable inside fun2(). In fun2, num has no effect of the global keyword. Before and after calling fun2() the num takes the value of the local variable i.e 24. Outside the fun1(), the num will take global variable i.e 100 because we have used the global keyword in num to create a global variable inside fun2() so, if we make any changes inside the fun2(), the changes appear outside the local scope i.e fun1()

def fun1():
    num = 24
    def fun2():
        global num
        num = 100
    print("Before calling fun1(): ", num)
    fun2()
    print("After calling fun2(): ", num)
fun1()
print("num Variable Outside both function(): ", num)

Output

Following is the output of the above code −

Before calling fun1():  24
After calling fun2():  24
num Variable Outside both function():  100

Using global Keyword in if-else statement

When the global keyword is used inside the if-else, it will raise an SyntaxError.

Example

Following is an example of usage of global keyword in if-else

var1 = 80
if True:
    global var1
    var1 = 234
    print(var1)

Output

Following is the output of the above code −

File "/home/cg/root/70237/main.py", line 3
    global var1
    ^^^^^^^^^^^
SyntaxError: name 'var1' is assigned to before global declaration
python_keywords.htm
Advertisements