In Python, the difference between local and global variables lies in their scope and accessibility:
-
Global Variables:
- Defined outside of any function.
- Accessible from any function within the same module.
- Can be modified inside a function using the
globalkeyword.
Example:
global_var = "I'm global" def access_global(): print(global_var) # Accessing global variable access_global() # Output: I'm global -
Local Variables:
- Defined within a function.
- Accessible only within that function.
- Cannot be accessed outside the function.
Example:
def local_variable_example(): local_var = "I'm local" print(local_var) # Accessing local variable local_variable_example() # Output: I'm local # print(local_var) # This would raise a NameError
In summary, global variables can be accessed from anywhere in the module, while local variables are confined to the function in which they are defined.
