Python Tutorial Python Advanced Python References Python Libraries

Python global Keyword



The Python global keyword is used to create a global variable from a non-global scope, for example - inside a function. A global variable can be used anywhere, inside a non-global scope and outside a non-global scope.

Example

In the example below, the global keyword is used to create a variable called MyString with global scope inside the function called MyFunction.

def MyFunction():
  global MyString
  MyString = "Python"

MyFunction()
print("Learning", MyString ,"is fun.")

The output of the above code will be:

Learning Python is fun.

Example

The value of a global variable, which is created outside of a function, can be changed inside the function by referring to the variable using the global keyword.

MyString = "Java"

def MyFunction():
  global MyString
  MyString = "Python"

MyFunction()
print("Learning", MyString ,"is fun.")

The output of the above code will be:

Learning Python is fun.

❮ Python Keywords