Local and global scope

Variables have different scopes, which determine where they can be accessed and used within a program. The two main scopes are local scope and global scope.

Local Scope

Variables defined inside a function have a local scope. This means they can only be accessed within that specific function. Local variables are created when the function is called and are destroyed when the function completes execution. Here's an example:

def my_function():
    x = 10  # Local variable
    print(x)

my_function()  # Output: 10
print(x)  # Error: NameError: name 'x' is not defined

In this example, the variable x is defined inside the my_function() function. It can only be accessed within the function. If we try to access x outside the function, we'll get a NameError because x is not defined in the global scope.

Global Scope

Variables defined outside any function or at the top level of a module have a global scope. This means they can be accessed from anywhere in the program, including inside functions. Global variables are created when they are first assigned a value and exist until the program terminates. Here's an example:

x = 10  # Global variable

def my_function():
    print(x)

my_function()  # Output: 10
print(x)  # Output: 10

In this example, the variable x is defined outside the function, making it a global variable. It can be accessed both inside and outside the function.

Click the run button to see the output. Then remove the global x line and run the code again to see the difference.

Modifying Global Variables Inside a Function

If you want to modify a global variable inside a function, you need to use the global keyword to indicate that you want to use the global variable, rather than creating a new local variable. Here's an example:

x = 10  # Global variable

def my_function():
    global x
    x = 20  # Modifying the global variable
    print(x)

my_function()  # Output: 20
print(x)  # Output: 20

In this example, we use the global keyword before modifying the value of x inside the function. This tells Python that we want to use the global variable x rather than creating a new local variable when we say x = 20 in the next line.

Global variables should be used sparingly and only when necessary. It is good practice to encapsulate variables within functions to avoid potential naming conflicts and improve code maintainability.