Python scope learning for beginner

Опубликовано: 15 Август 2025
на канале: Dev Sihag
9
3

In Python, scope means where in your code a variable can be accessed or used.

Think of it like rooms in a house:

If a toy is in your bedroom (local scope), only you can play with it inside that room.

If the toy is in the living room (global scope), everyone in the house can use it.

If the toy is in the neighbor’s house (built-in scope), you can use it only if you go there.

Python follows the LEGB Rule to find variables:

Local (L) – Variables created inside the current function.

Enclosing (E) – Variables from any outer functions (in case of nested functions).

Global (G) – Variables created at the top level of the script (outside functions).

Built-in (B) – Predefined variables/functions provided by Python (like print, len).

When you try to use a variable, Python searches in this order:
Local → Enclosing → Global → Built-in
If it can’t find it anywhere, you get a NameError.

📝 10 Examples – Basic to High Level
1. Local Scope – Function Variable
def my_function():
x = 10
print(x) # Accessible here

my_function()
print(x) # ❌ Error: x is not defined outside the function


Explanation: Variable x exists only inside the function.

2. Global Scope – Variable Everywhere
y = 20 # Global

def show():
print(y) # Accessible inside function

show()
print(y) # Accessible outside too


Explanation: Global variables can be accessed anywhere in the file.

3. Function Accessing Global Variable
z = 30

def display():
print(z) # Uses global z

display()


Explanation: If Python doesn’t find z locally, it looks for it globally.

4. Changing Global Variable Inside Function (global keyword)
count = 0

def increment():
global count
count += 1

increment()
increment()
print(count) # Output: 2


Explanation: global lets you modify a global variable from inside a function.

5. Enclosing Scope – Nested Functions
def outer():
msg = "Hello"
def inner():
print(msg) # Accesses from enclosing scope
inner()

outer()


Explanation: Inner function can access outer function variables.

6. Changing Enclosing Variable with nonlocal
def outer():
msg = "Hi"
def inner():
nonlocal msg
msg = "Hello"
inner()
print(msg)

outer() # Output: Hello


Explanation: nonlocal changes the variable from the enclosing scope.

7. Local vs Global Variable Conflict
name = "Global"

def func():
name = "Local"
print(name) # Local wins

func()
print(name) # Global still unchanged


Explanation: Local variables override global variables inside a function.

8. Built-in Scope
print(len("Python")) # len() is from built-in scope

Overriding built-in (Not recommended)
len = 100
print(len("abc")) # ❌ Error now


Explanation: Built-in names are always available unless overridden.

9. Scope Inside Loops and Conditionals
if True:
a = 50 # This is global if not in a function

print(a) # Accessible here


Explanation: Python has no block scope for if/for — variables are global unless inside a function.

10. Scope with List Comprehension
nums = [1, 2, 3]
squares = [n*n for n in nums]
print(squares)

print(n) # Output: 3 (last value from comprehension)In Python, scope means where in your code a variable can be accessed or used.

Think of it like rooms in a house:

If a toy is in your bedroom (local scope), only you can play with it inside that room.

If the toy is in the living room (global scope), everyone in the house can use it.

If the toy is in the neighbor’s house (built-in scope), you can use it only if you go there.

Python follows the LEGB Rule to find variables:

Local (L) – Variables created inside the current function.

Enclosing (E) – Variables from any outer functions (in case of nested functions).

Global (G) – Variables created at the top level of the script (outside functions).

Built-in (B) – Predefined variables/functions provided by Python (like print, len).

When you try to use a variable, Python searches in this order:
Local → Enclosing → Global → Built-in
If it can’t find it anywhere, you get a NameError.

📝 10 Examples – Basic to High Level
1. Local Scope – Function Variable
def my_function():
x = 10
print(x) # Accessible here

my_function()
print(x) # ❌ Error: x is not defined outside the function


Explanation: Variable x exists only inside the function.

2. Global Scope – Variable Everywhere
y = 20 # Global

def show():
print(y) # Accessible inside function

show()
print(y) # Accessible outside too


Explanation: Global variables can be accessed anywhere in the file.

3. Function Accessing Global Variable
z = 30

def display():
print(z) # Uses global z

display()


Explanation: If Python doesn’t find z locally, it looks for it globally.

4. Changing Global Variable Inside Function (global keyword)
count = 0

def increment():
global count
count += 1

increment()
increment()
print(count) # Output: 2


Explanation: global lets you modify a global variable from inside a


На этой странице сайта вы можете посмотреть видео онлайн Python scope learning for beginner длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь Dev Sihag 15 Август 2025, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 9 раз и оно понравилось 3 зрителям. Приятного просмотра!