When working with variables in Python, it’s important to understand their scope - where they are visible and accessible within your program. The scope of a variable depends on where it is declared.

Global Variables

When a variable is declared outside of any function, it is considered a global variable. Global variables are accessible to any part of the program, including functions. Here’s an example:

age = 8

def test():
    print(age)

print(age) # Output: 8
test()     # Output: 8

In this example, age is a global variable. It is accessible both inside and outside the test() function. When we print age before and after calling the test() function, it outputs 8 in both cases.

Local Variables

When a variable is declared inside a function, it is considered a local variable. Local variables have a limited scope and are only accessible within the function where they are defined. Here’s an example:

def test():
    age = 8
    print(age)

test()     # Output: 8

print(age) # NameError: name 'age' is not defined

In this example, age is a local variable within the test() function. It is only accessible inside the function and cannot be accessed outside of it. When we try to print age outside the test() function, it raises a NameError.

Understanding variable scope is crucial for writing clean and bug-free Python code. By properly defining the scope of variables, you can avoid conflicts and ensure that your code is more maintainable.