Scope of variables (Global, Local)

SEO optimization. Modern tech. PHP syntax highlighted. Writing programming functions on laptop. Big data and Internet of things trend.

Global Scope

A variable that is defined outside of any function has a global scope, which means it is accessible from anywhere within the program. Global variables can be read and changed from any part of the code.

Here is an example:

x = 10  # Global scope

def func():
    global x
    x = 20  # Accessing the global variable to modify it

def main()
    func()
    print(x)  # Output: 20

Local Scope

A variable that is defined within a function has a local scope. It is only accessible within that function and not from outside of it. Each time a function is called, a new local scope is created for that call, and any local variables are only valid within that scope.

Example:

def func():
    y = 5 # Local scope
    print(y) # Accessible here

def main()
    func()
    print(y) # This will result in a NameError as y is not accessible outside func()