In Python, a variable's scope refers to the part of the program where that variable is accessible. There are two main types of variable scope in Python: global and local.
Global Scope: Variables that are defined outside of a function are called global variables, and they are accessible from anywhere in the program. Global variables can be accessed and modified by any function in the program. Here's an example:
x = 10 # global variabledef my_function(): print(x) # prints the global variable xmy_function() # Output: 10 |
In this example, x is defined outside of the function my_function, so it has global scope. The function my_function can access and print the value of x.
Local Scope: Variables that are defined inside of a function are called local variables, and they are only accessible within that function. Local variables can't be accessed or modified by functions outside of their scope. Here's an example:
def my_function(): x = 10 # local variable print(x)my_function() # Output: 10print(x) # NameError: name 'x' is not defined |
In this example, x is defined inside the function my_function, so it has local scope. The function can access and print the value of x, but once the function finishes executing, x is no longer accessible outside of the function's scope.
It's important to be aware of variable scope when writing functions, especially when using global variables, as they can lead to unexpected behavior if not used carefully.