Global keyword in Python

Overview:

  • From an inner scope, the global keyword in Python binds a name to the global scope, so that a global variable can be assigned a value. 
  • Usage of global is not required, if the requirement is only to access the variable in the global scope but not assigning a value to it.
  • Global scope is the outermost or topmost scope in Python.
  • The difference between the keyword global and the keyword nonlocal is, global binds a name from an inner scope, directly to the next-to-last scope - global(The last scope or the outtermost scope is the namespace containing builtin names), while the nonlocal binds a name to the next outer scope, where that name is available.

How global can not be used:

  • In the same code block, using a name as local for some distance (time) and using it as global for some distance (time) is not allowed.
  • A formal parameter of a function cannot be defined as global inside that function.

Example – Behaviour while using the global keyword:

# Example Python program that uses the global

# keyword to bind a name to the global scope

msg = "Hi";

 

def function1():

    global msg;

    msg = "Hello";

    print("Function1:",msg);

   

function1();

print("Global:", msg);

 

Output:

Function1: Hello

Global: Hello

 

Example - Behaviour while not using the global keyword:

# Example Python program that uses the global

# keyword to bind a name to the global scope

msg = "Hi";

 

def function1():

    msg = "Hello";

    print("Function1:",msg);

   

function1();

print("Global:", msg);

 

Output:

Function1: Hello

Global: Hi

 


Copyright 2024 © pythontic.com