Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used. Python supports global variables (usable in the entire program) and local variables.
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
In Python, a variable declared outside of the function or in global scope is known as a global variable. This means the global variables can be accessed inside or outside of the function.
Let’s see an example of how a global variable is created in Python.
x = "global" def abc(): print("x inside :", x) #function call abc() print("x outside:", x)
x inside : global
x outside: global
def abc(): print("x inside :", x) x=100 abc() print("x outside:", x)
x inside : 100
x outside: 100