Global keyword in Python program

PythonServer Side ProgrammingProgramming

Sometimes we declare a variable but we may need to modify or access the values outside the current scope of its declaration which may be anywhere in the current program. In such scenario, we use the Global keyword with the variable name inside the function where the variable is declared. If the variable is not inside a function, then it is automatically global in scope.

Variable Outside a Function

In the below example we see a value outside a function, but we are able to access it from inside a function. Because such a variable is already global in scope.

Example

x = 56
def func():
y = x *2
   return y
print(func())

Running the above code gives us the following result:

Output

112

Variable Inside a Function

In the next example we attempt to change the value of a variable inside a function and get an error.

Example

x = 56
def func():
   y = x *2
   x = x+2
      return y
print(func())

Running the above code gives us the following result:

Output

nboundLocalError: local variable 'x' referenced before assignment

The only way we can modify the value of a variable with global scope inside a function is by declaring it as a global variable inside a function.

Example

x = 56
def func():
global x
   x = x + 2
   y = x *2
      return y
print(func())

Running the above code gives us the following result

Output

116

Variable Inside a Nested Function

In case of nested function, we create the global variable in the innermost function as shown in the below example.

Example

 Live Demo

def func_out():
   x = 56
   def func_in():
      global x
      x = 20
      print("x is: ",x)
      x = x + 3
      y = x *2
      print ("y is: ",y)
   func_in()
func_out()
print("x is: ",x)

Running the above code gives us the following result:

Output

x is: 20
y is: 46
x is: 23
raja
Updated on 20-Dec-2019 10:48:53

Advertisements