
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Global keyword in Python program
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
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
- Related Articles
- Global keyword in Python
- Finally keyword in Python
- Keyword arguments in Python
- assert keyword in Python
- Global and Local Variables in Python?
- Global vs Local variables in Python
- Program to check number of global and local inversions are same or not in Python
- How to declare a global variable in Python?
- Python program to check if a given string is Keyword or not
- C Program to Redeclaration of global variable
- Golang program that uses fallthrough keyword
- How to use a global variable in a Python function?
- How do I declare a global variable in Python class?
- How do I share global variables across modules in Python?
- Explain the visibility of global variables in imported modules in Python?
