image
image
image

Global Keyword in Python

image

The global keyword I Python allows modification of the variable outside the current scope. The global keyword makes changes to the variable in a local context. There are rules when creating a global keyword:

A global keyword is local by default when we create a variable within a function.

It is global by default when we define a variable outside of a function and you do not need to use the global keyword.

The global keyword is used to read and write a global variable within a function.

The use of global keyword outside a function will have no effect.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number = 3  #A global variable

def add():

print(number)

add()

The output of this program will be 3.

Modifying global variable from inside the function.

number=3  #a global variable 

def add():

number= number + 4  # add 4 to 3

print(number)

add()

Discussion

When the program is executed it will generate an error indicating that the local variable number is referenced before assignment. The reason for encountering the error is because the global variable can only be accessed but it is not possible to modify it from inside the function. Using a global keyword would solve this.

Example

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

Modifying global variable within a function using the global keyword.

number = 3  # a global variable

def add():

global number

number= number + 1 # increment by 1

print("Inside the function add():", number)

add()

print("In main area:", number)

Discussion

When the program is run, the output will be:

Inside the function add(): 4

In the main area: 4

We defined a number as a global keyword within the function add(). The variable was then incremented by 1, variable number. Then we called the add () function to print global variable c.