In python, if you want to create a local variable inside the function and you want to access the same variable outside of the function as a global variable, then you need to define the variable with the global
keyword.
Generally, if you create a variable inside of the function, that variable scope is limited to within that function but by using the global
keyword, you can create global variables inside of the function.
Following is the example of creating the global variable inside of the function using the global
keyword in python.
If you observe the above example, we created a global variable (msg) inside of the greeting() function using a global
keyword, and we are accessing the same variable outside of the function.
When you execute the above python example, you will get the result as shown below.
In some scenarios, we are not allowed to change the value of global variables inside of the function.
Following is the example of changing the global variable value inside of the function in python.
When you execute the above python program, you will get the exception as shown below.
In this case, the global
keyword is useful to make changes to the global variables inside of the function.
Following is the example of changing the value of the global variable inside of a function using the global
keyword in python.
If you observe the above example, we are modifying the value of the global variable (msg) inside of the function by using the python global
keyword.
When we execute the above program, we will get the result as shown below.
If you observe the above result, the global variable (msg) value has been updated with the changes we made in the calculate function.