Login Register

What Is a Scope In Python?

What Is a Scope?

A Scope means where you can access a particular variable in your program. In Programming, every variable we create inside some boundary, and that boundary decides two things:

  • Where the variable can be accessed
  • How long the variable stays alive

You can consider a scope as the rooms in a house. If a variable is created inside the kitchen (inside a function), then you cannot use it directly from the bedroom (outside of the function).

A scope is essential for writing efficient and bug-free code because it determines the visibility of variables in a particular area.

What Is The LEGB Rule In Python?

Python follows a specific set of rules to find variables. These rules are called the LEGB Rule, and they help us to decide:

  • Which variable to use?
  • From where should it fetch the value?

Python search a variable in this exact order:

1) L → Local Scope: This variable exists inside a function, and it’s created when the function starts and destroyed when the function ends.

2) E → Enclosing Scope: These variables work inside the outer function in nested functions.

3) G → Global Scope: This refers to a variable defined at the top level of the script.

4) B → Built-in Scope: This contains predefined names in Python like len(), print(), range(), etc.

Python checks scopes in the top-to-bottom order:

Local → Enclosing → Global → Built-in

It will give this type of error when it can’t find a variable anywhere:

NameError: variable is not defined

Types of Scope in Python

  1. Local Scope
  2. Enclosing Scope
  3. Global Scope
  4. Built-in Scope

1. Local Scope

These variables exist only while the function is running and are then destroyed when the function finishes.

Local variables are like temporary notes on a whiteboard in a classroom; when the class ends, the board will be cleaned.

Example of Local Scope

Calculating a Temporary Discount Inside a Function

def apply_discount(price):
discount = price * 0.10 # Local variable (only inside this function)
final_price = price - discount
print("Price after discount:", final_price)

apply_discount(500)

# Trying to access discount here will give an error
# print(discount) # Not allowed (local variable)

Output:

Price after discount: 450.0
  • Here, discount and final_price stay only inside apply_discount().

2. Enclosing Scope

Enclosing works in nested functions means one function inside another function. It means both inner and outer function allows us to work with one variable.

Example of Enclosing Scope

We create a temperature converter using an enclosing scope.

def converter(unit):
message = f"Converting temperature to {unit}"

def change(value):
print(message)
if unit == "Celsius":
return (value - 32) * 5/9
else:
return (value * 9/5) + 32

return change


to_celsius = converter("Celsius")
to_fahrenheit = converter("Fahrenheit")

print(to_celsius(86)) # Converts Fahrenheit → Celsius
print(to_fahrenheit(30)) # Converts Celsius → Fahrenheit

3. Global Scope

Global scope means your variables live in all outside functions, and they can be accessed from anywhere inside the file.

Example of Global Scope

Reading a Global Variable Inside a Function

# Global variable
website_name = "BoxOfLearn"

def display_site():
print("You are learning on:", website_name)

display_site()

Output of the code:

You are learning on: BoxOfLearn

How To Modify a Global Variable?

We will use the global keyword to modify the variable.

# Global counter
visits = 0

def record_visit():
global visits # Permission to modify global variable
visits += 1
print("Visit recorded! Total visits:", visits)

record_visit()
record_visit()

Final output:

Visit recorded! Total visits: 1
Visit recorded! Total visits: 2
  • You can see, we have used a global visits to tell Python: “I want to update the outside variable, not create a new one.”

4. Built-in Scope

Built-in scope means Python provides pre-defined keywords of functions, errors, and types, such as:

  • Built-in functions → print(), len(), max(), min()
  • Built-in errors → TypeError, ValueError
  • Built-in types → int, str, list, etc.

It means we don’t need to import anything or create anything.

Example of Built-in Scope

Using a built-in name (len) inside different scopes

# Using built-in function 'len'

greeting = "Hello Python!"

def check_length():
word = "Scope"
print("Length inside function:", len(word)) # using built-in len()

check_length()

print("Length in global scope:", len(greeting)) # using len again globally

Output of built-in scope:

Length inside function: 5
Length in global scope: 13

What Is the nonlocal Keyword in Python?

Sometimes, we want the inner function to update an outer function variable, but Python does not allow the inner function to change the outer variable directly.

In this case, we used a nonlocal keyword. For example:

def create_click_counter():
clicks = 0 # Enclosing variable

def click_button():
nonlocal clicks # Use and modify the enclosing 'clicks'
clicks += 1
print(f"Button clicked {clicks} times")

return click_button


# Using the counter
counter = create_click_counter()
counter() # Button clicked 1 times
counter() # Button clicked 2 times

Common Errors We Face In The Scope

We can face two scope-related issues:

  • UnboundLocalError
  • Variable Shadowing

1) UnboundLocalError: This error happens when we try to change a variable inside a function, but Python thinks we are creating a new local variable.

Let’s see the example:

level = 1   # global variable

def upgrade():
level = level + 2 # Python thinks this 'level' is LOCAL
print("Level inside function:", level)

upgrade()

Explanation:

  • Python sees level = level + 2
  • It assumes you want to create a local variable level
  • But you’re also trying to read level before assigning it locally
  • No local value exists yet
  • Boom! UnboundLocalError

You can correct it using a global keyword:

level = 1

def upgrade():
global level #explicitly use the global variable
level = level + 2
print("Updated level inside function:", level)

upgrade()
print("Level outside function:", level)

Output:

Updated level inside function: 3
Level outside function: 3

2) Shadowing: When a Local Variable Hides a Global One

This error happens when you use the same variable name inside a function AND outside it. The local variable “hides” the global one, and the function will only use the local version.

This is not technically an error, but it can cause unexpected or confusing results.

message = "This is a global message"

def show_message():
message = "This is a local message" # shadows the global variable
print("Inside function:", message)

show_message()
print("Outside function:", message)

Output:

Inside function: This is a local message
Outside function: This is a global message