Resources | Subject Notes | Computer Science
In programming, the scope of a variable determines where in the code that variable can be accessed. Understanding local and global scope is crucial for writing correct and maintainable programs. This section explains the differences between these two types of scope.
A global variable is declared outside of any function or block of code. This means it can be accessed from anywhere in the program – both inside and outside of functions.
A local variable is declared inside a function or a specific block of code (e.g., within an `if` statement or a loop). It can only be accessed within that function or block.
Consider the following example in Python:
Scope | Declaration | Accessibility |
---|---|---|
Global | Declared outside any function. | Accessible from anywhere in the program. |
Local | Declared inside a function or block. | Accessible only within the function or block. |
Here's a simple Python code snippet to demonstrate the difference:
global_var = 10 def my_function(): local_var = 5 print("Inside function:") print("Global variable:", global_var) print("Local variable:", local_var) my_function() print("Outside function:") print("Global variable:", global_var) # print("Local variable:", local_var) # This would cause an error!
In this example, global_var
is a global variable and local_var
is a local variable within my_function
. Attempting to access local_var
outside of my_function
would result in an error.
Using appropriate variable scope helps to: