Global in Nested functions
In order to use global inside a nested function, we have to declare a variable with a global keyword inside a nested function
Python3
# Python program showing a use of # global in nested function def add(): x = 15 def change(): global x x = 20 print ( "Before making changing: " , x) print ( "Making change" ) change() print ( "After making change: " , x) add() print ( "value of x" , x) |
Output:
Before making changing: 15 Making change After making change: 15 value of x 20
In the above example Before and after making change(), the variable x takes the value of local variable i.e x = 15. Outside the add() function, the variable x will take the value defined in the change() function, i.e x = 20. Because we have used global keyword in x to create a global variable inside the change() function (local scope).
Global keyword in Python
In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python.