global keyword in Python

The global keyword in Python allows a name in an inner scope to be bound with the global scope. The Python example code demonstrates a scenario with and without using the global keyword.

Keywords Updated 12 Sep 2019 1 min read

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

python
# 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

Output
Function1: Hello

Global: Hello

Example - Behaviour while not using the global keyword

python
# 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

Output
Function1: Hello

Global: Hi

##