0
0
PythonConceptBeginner · 3 min read

What is Scope of Variable in Python: Explanation and Examples

In Python, the scope of a variable is the area of the program where that variable can be accessed or used. Variables defined inside a function have a local scope, meaning they can only be used within that function, while variables defined outside any function have a global scope and can be accessed anywhere in the program.
⚙️

How It Works

Think of variable scope like rooms in a house. A variable defined inside a function is like a toy kept in a child's room — only the child (the function) can play with it. This is called local scope. Once you leave the room, you can't see or use that toy.

On the other hand, a variable defined outside any function is like a family photo hung in the living room — everyone in the house can see and use it. This is called global scope. Python keeps track of where variables are created and only allows access to them within their scope.

This helps avoid confusion and mistakes by keeping variables organized and limiting where they can be changed or read.

💻

Example

This example shows a global variable and a local variable inside a function. Notice how the local variable is only accessible inside the function.

python
x = 10  # global variable

def show_values():
    y = 5  # local variable
    print(f"Inside function: x = {x}, y = {y}")

show_values()
print(f"Outside function: x = {x}")
# print(y)  # This would cause an error because y is local
Output
Inside function: x = 10, y = 5 Outside function: x = 10
🎯

When to Use

Understanding variable scope helps you write clear and bug-free code. Use local variables inside functions to keep temporary data private and avoid accidental changes from other parts of your program. Use global variables when you need to share data across multiple functions or parts of your program.

For example, in a game, you might keep the player's score as a global variable so many functions can update it, but keep the current level's temporary settings as local variables inside the level function.

Key Points

  • Local variables exist only inside the function where they are created.
  • Global variables exist throughout the entire program.
  • Trying to access a local variable outside its function causes an error.
  • Use the global keyword to modify a global variable inside a function if needed.

Key Takeaways

Variable scope defines where a variable can be accessed in Python code.
Local variables live inside functions and are hidden outside them.
Global variables are accessible anywhere in the program.
Use local scope to keep data private and global scope to share data.
Accessing a variable outside its scope causes an error.