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.