Global variables in Python
In Python, as is in many programming languages, global variables are variables that are accessible anywhere in a class unless shadowed by a local variable inside the same class. More of classes in a later tutorial. Local variables are those declared inside a function and are only accessible in that function only. We say their scope is local to that function where they are declared in.
How to declare a global variable in Python
Mainly a global variable in Python is declared outside a function. The global variable can then be used inside functions.
Example
On running the above program, we get below results
Changing value of a global variable inside a function changes value within the function only-not outside the function
When the value of a global variable is changed inside a function, its new value is local to the function in which the change is made. The global value is retained and access to the global variable gives the initial old value
Example
When we run the above program we get output as below
Global keyword-changing the value of a global variable in a function
We use the global to modify the value of a global variable inside a function. Using our earlier example lets proceed to see this in action
On running the above program we get the output as below
Global variable cannot be modified inside a function, unless we use the global keyword
Suppose we want to change/modify the value of a global variable inside a function, we will not succeed unless we use the global keyword.
Let’s see this with an example
When we run the above program we get output as below
Let’s remedy by using the global variable as seen earlier so that we are able to modify the name global variable
When we run the above program, we get the output below
Create global variables from inside a function
Global variables can be created from inside a function by using the global keyword.
Lets see two(2) scenarios ,whereby one, a local variable is accessed outside the function it is defined in and the other whereby a local variable is made global.
Example
When the above program is run, we get below output
On line 10 we are trying to access name variable which is local to function printname() and not visible on line 10.
Let’s remedy this scenario
Once we run the above program , the output is as below