Python Scope

Scope refers to the visibility and lifetime of variables and other resources in your Python code. Understanding scope is important because it determines where you can access variables and how long they exist. In this lesson, we will cover the basics of scope in Python and how it works.

Global Scope

Variables defined outside of any function have global scope, which means they can be accessed from anywhere in the code. For example:

x = 10  # Global variable

def my_function():
    print(x)  # Accessing global variable

my_function()  # Output: 10

Local Scope

Variables defined inside a function have local scope, which means they can only be accessed from within that function. For example:

def my_function():
    y = 20  # Local variable
    print(y)

my_function()  # Output: 20

# Trying to access y outside the function will result in an error
# print(y)  # Error: NameError: name 'y' is not defined

Global Keyword

If you need to modify a global variable from within a function, you can use the globalkeyword to declare that you want to use the global variable, rather than creating a new local variable. For example:

x = 10

def my_function():
    global x  # Using the global keyword
    x = 20

my_function()
print(x)  # Output: 20

Conclusion

Scope in Python determines the visibility and lifetime of variables. By understanding global and local scope, as well as how to use the global keyword, you can write more effective and maintainable Python code.



[ Footer Placeholder]