Curriculum
In Python, variable scope refers to the region of a program where a variable can be accessed. The scope of a variable is determined by where it is defined in the program, and it affects how the variable can be used and modified. There are two main types of variable scope in Python: local scope and global scope.
Local scope: A variable that is defined inside a function has local scope, which means it can only be accessed within that function. If you try to access a local variable from outside the function, you’ll get a NameError. Here’s an example:
def my_function(): x = 5 print(x) my_function() print(x) # NameError: name 'x' is not defined
In this example, the variable x
is defined inside the my_function
function, so it has local scope. We can access and modify x
inside the function, but we can’t access it from outside the function.
global
keyword to indicate that you want to modify the global variable, rather than create a new local variable with the same name. Here’s an example:x = 5 # global variable def my_function(): global x x = 10 print(x) my_function() print(x) # 10
In this example, we define the variable x
outside any function, so it has global scope. We can access and modify x
from anywhere in the program, including inside the my_function
function. However, because we want to modify the global variable x
inside the function, we need to use the global
keyword to indicate that we’re referring to the global variable, not creating a new local variable with the same name.
In summary, variable scope in Python determines where a variable can be accessed and modified in the program. Variables with local scope can only be accessed within the function where they are defined, while variables with global scope can be accessed from anywhere in the program. If you want to modify a global variable inside a function, you need to use the global
keyword to indicate that you’re referring to the global variable.