![]() |
VOOZH | about |
The global keyword in Python allows a function to modify variables that are defined outside its scope, making them accessible globally. Without it, variables inside a function are treated as local by default. It's commonly used when we need to update the value of a global variable within a function, ensuring the changes persist outside the function.
Example:
20
Explanation: This code uses the global keyword inside the function to modify the global variable x. By calling fun(), the global x is updated to 20 .
Output:
25Explanation: In this example, the global variables a and b are accessed inside the function without needing the global keyword because we are just referencing them.
Output:
UnboundLocalError: local variable 'a' referenced before assignmentExplanation: Here, Python assumes a is a local variable inside the function since we try to assign a value to it. To modify the global a, we need to use the global keyword.
20 20
Explanation: In this example, we first define x as a global keyword inside the function change(). The value of x is then incremented by 5, i.e. x=x+5 and hence we get the output as 20. As we can see by changing the value inside the function change(), the change is also reflected in the value outside the global variable.
Unlike immutable objects (e.g., integers, strings), mutable objects (e.g., lists, dictionaries) can be modified without needing the global keyword.
Here, we can modify list elements defined in global scope without using global keyword. Because we are not modifying the object associated with the variable a, but we are modifying the items the list contains. Since lists are mutable data structures, thus we can modify its contents.
before [10, 20, 30] after [20, 30, 40]
Here we are trying to assign a new list to the global variable. Thus, we need to use the global keyword as a new object is created. Here, if we don't use the global keyword, then a new local variable a will be created with the new list elements. But the global variable arr will be unchanged.
before [10, 20, 30] after [20, 30, 40]
global keyword is also useful when we need to share global variables between different Python modules. We can define a separate configuration module to hold global variables and import them into other modules.
Output:
1
2
geeksforgeeks
Explanation : In this example, the variables x, y, and z are defined in config.py, modified in modify.py, and then accessed in main.py. This is an efficient way to share global variables across different modules.
In order to use global inside a nested function, we have to declare a variable with a global keyword inside a nested function
Before changing: 15 Making change After changing: 15 Value of x outside: 20
Explanation: In this example, the outer function add has a local variable x. The nested function change modifies the global x. The changes to x are reflected outside the function.