Scope
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.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
Global Scope
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.
Global Variables
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.
Example:1
x = "global" def abc(): print("x inside :", x) #function call abc() print("x outside:", x)
Output:
x inside : global
x outside: global
Example:2
def abc(): print("x inside :", x) x=100 abc() print("x outside:", x)
Output:
x inside : 100
x outside: 100