Skip to content

4.2.1 Local and Global Variables

Variables in Python exist within different scopes.
Scope determines where a variable can be accessed and modified.


Local Variables

Local variables:

  • Are defined inside a function
  • Exist only within that function
  • Are created when the function is called

They help isolate data and prevent unintended side effects.


Global Variables

Global variables:

  • Are defined outside of functions
  • Can be accessed throughout the program
  • Should be used sparingly

Modifying global variables inside functions can reduce code clarity.


📌 Note:
Prefer local variables to avoid unexpected interactions between different parts of a program.