

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Global keyword in Python
Different variables in a python program have different scope. Depending on where it is declared, the variable may or may not be accessible inside a function. Sometimes we will need to modify a variable that is present inside a function from outside its current scope. In such a scenario we use the global keyword with the variable name.
Following are the key points about the global keyword
A variable declared outside a function is a global variable by default.
We use a global keyword for a variable which is inside a function so that it can be modified.
Without the global keyword, the variable inside a function is local by default.
Without Global
In the below examples we will see how the variable change happens without a global keyword. This will help us understand, what difference the global keyword makes in the next program. In the below example we try to modify the global variable inside the function. But an error occurs as we can not modify a global variable inside a function.
Example
var = 321 # function to modify the variable def modify(): var = var * 2 print(var) # calling the function modify()
Output
Running the above code gives us the following result −
UnboundLocalError: local variable 'var' referenced before assignment
With Global
Now we declare the variable inside the function along with the keyword global. This makes the variable modifiable.
Example
var = 321 # function to modify the variable def modify(): global var var = var * 2 print(var) # calling the function modify()
Output
Running the above code gives us the following result −
642
Global within Nested Functions
If we have to use nested functions then we have to declare the global keyword in the inner function so that the variable can be modified.
Example
def outer_func(): var = 321 # function to modify the variable def modify(): global var var = var * 2 print(var) # calling the function modify() outer_func()
Output
Running the above code gives us the following result −
642
- Related Questions & Answers
- Global keyword in Python program
- Finally keyword in Python
- assert keyword in Python
- Keyword arguments in Python
- Global and Local Variables in Python?
- Global vs Local variables in Python
- How to declare a global variable in Python?
- Global variables in Java
- What is the Python Global Interpreter Lock (GIL)
- JavaScript global Property
- PHP Global space
- How to use a global variable in a Python function?
- How do I declare a global variable in Python class?
- Global Scope Variables in Postman?
- Global Variables in Lua Programming