python global variable
Python hosting: Host, run, and code Python in the cloud!
There are two primary types of variables in Python: global variables and local variables.
A global variable is accessible throughout the code, whereas a local variable is limited to its defined scope.
In the diagram above, the global variable (x) is available throughout the code, while the local variable (z) is confined to block 3.
Recommended Course: Python Programming Bootcamp: Go from zero to hero
Local Variables
Local variables are confined to their defined scope.
In the following example, x
and y
are local variables:
def sum(x,y): |
Here, x
and y
are only accessible within the sum
function and are not recognized outside it.
Thus, attempting to print a local variable outside its scope, like this:
print(x) |
will result in an error.
Global Variables
In contrast, a global variable is available throughout your entire code.
Below is an example of a global variable, z
:
z = 10 |
Whether inside or outside a function, the global variable z
is accessible.
Moreover, you can modify a global variable within a function, impacting its value throughout the entire program:
z = 10 |
After invoking afunction()
, the value of the global variable changes for the entire program.
Exercise
Both local and global variables can coexist in a single Python program.
Examine the following code and predict its output:
z = 10 |
Leave a Reply: