Home Tutorials Python Tutorial Variable Scope
Variable Scope

Variable Scope


Definition: Variable scope refers to the region of a program where a particular variable is accessible and can be used. In Python, variables can have either a local scope or a global scope.

Why: Scope is an important concept when working with functions because it prevents different parts of your program from accidentally changing or breaking variables they shouldn't have access to.

Types of Scope

  • Global Scope: A variable created in the main body of the Python script is a global variable. It can be seen and accessed by any code in the file, including inside functions.
  • Local Scope: A variable created inside a function belongs to the local scope of that function. It can only be used inside that specific function and cannot be accessed from the outside.

Example

x = 100  # Global variable

def show():
    y = 20  # Local variable
    print(x)  # Accessing global variable inside the function
    print(y)  # Accessing local variable inside the function

show()

# print(y)  # This would cause a NameError because y does not exist outside show()

Explanation

  • x is declared outside the function, making it a global variable. The show() function can read its value without any issues.
  • y is declared inside the show() function, making it a local variable. It is created when the function is called and destroyed as soon as the function finishes executing.
  • If you uncomment the last line of the example, the program will crash because the main script has no idea what y is.

Key Notes

  • If you want to modify a global variable from inside a function, you must declare it using the global keyword (e.g., global x) inside the function before changing it.
  • If a local variable and a global variable share the exact same name, Python will prioritize the local variable when executing code inside that specific function.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Variable Scope to test your knowledge.

Exercise »