Back to course

Understanding Variable Scope (Local vs Global)

Python Programming: The 0 to Hero Bootcamp

Variable Scope

Scope refers to the region of a program where a variable is accessible. Understanding scope prevents bugs where variables unexpectedly change or are unavailable.

1. Local Scope

Variables defined inside a function are local. They only exist while the function is executing and cannot be accessed from outside.

python def my_function(): local_var = 100 # Local scope print(local_var)

my_function() # Output: 100

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

2. Global Scope

Variables defined outside of any function are global. They can be accessed from anywhere in the module.

python global_count = 0

def increment_count(): # Functions can READ global variables print(f"Inside function, global count is: {global_count}")

increment_count()

The global Keyword

If you need to modify a global variable from within a local scope, you must explicitly declare it using the global keyword.

python global_setting = 'Off'

def toggle_setting(): global global_setting # Declare intent to modify the global variable global_setting = 'On' print(f"Setting toggled to: {global_setting}")

toggle_setting() print(f"Outside function: {global_setting}") # Output: On