Global Scope

Global Scope


A variable, with global scope can be used anywhere in the program. It can be created by defining a variable outside the scope of any function/block.

Rules of global Keyword

The basic rules for global keyword in Python are:

  • When we define a variable outside a function, it’s global by default. You don’t have to use global keyword.
  • We use global keyword to read and write a global variable inside a function.
  • Use of global keyword outside a function has no effect

Use of global Keyword

Example : Accessing global Variable From Inside a Function

c = 1 # global variable
def add():
print(c)
add()

Output:

1

Example : Accessing global Variable From Inside a Function

c = 1 # global variable
def add():
print(c)
add()

Output:

1

Example : Modifying Global Variable From Inside the Function

c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()

Output:

Unbound Local Error: local variable 'c' referenced before assignment

Example : Changing Global Variable From Inside a Function using global keyword

x = 0 # global variable
def add():
global x
x = x + 5 # increment by 2
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)

Output:

Inside add() function x value is : 5

In main x value is : 5

In the above program, x is defined as a global variable. Inside the add() function, global keyword is used for x and we increment the variable x by 5. Now We can see the change on the global variable x outside the function i.e the value of x is 5.

Python : Global Scope Program List




Program [1]

Write a Python program to show the application of Global variable.


View Solution


CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad