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 are confined to their defined scope.
In the following example,
y are local variables:
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:
will result in an error.
In contrast, a global variable is available throughout your entire code.
Below is an example of a global variable,
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
afunction(), the value of the global variable changes for the entire program.
Both local and global variables can coexist in a single Python program.
Examine the following code and predict its output:
z = 10