-
Hajipur, Bihar, 844101
Scope refers to the visibility or lifetime of a variable — where in the code you can access it. Python has different types of scopes depending on where the variable is declared.
A variable created inside a function is in the local scope and can only be used inside that function.
def greet():
name = "Alice"
print("Hello", name)
greet()
# print(name) # This will cause an error
A variable created outside of any function is in the global scope and can be used anywhere in the code (except inside a function unless declared global).
city = "Delhi"
def show():
print(city)
show()
To use or modify a global variable inside a function, you must declare it using the global
keyword.
count = 0
def update():
global count
count = 5
update()
print(count) # Output: 5
Variables in the outer function can be accessed in the inner function using the nonlocal
keyword.
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
print("Inner:", x)
inner()
print("Outer:", x)
outer()
Python has some built-in names like len()
, range()
, print()
, etc. These are available globally.
print(len("scope")) # Output: 5
Python follows the LEGB rule to decide the order of scope resolution:
L - Local
E - Enclosing
G - Global
B - Built-in
Q1. Write a Python program to create a function with a local variable and print it inside the function.
Q2. Write a Python program to declare a global variable and access it inside a function using the variable name directly.
Q3. Write a Python program to modify a global variable inside a function using the global
keyword.
Q4. Write a Python program to try accessing a local variable outside its function and observe the error.
Q5. Write a Python program to create nested functions and use nonlocal
to modify a variable from the outer function.
Q6. Write a Python program to use the same variable name in global and local scope and print both.
Q7. Write a Python program to override a built-in name like sum
and observe the effect.
Q8. Write a Python program to build a calculator that updates a global result
variable after each operation.
Q9. Write a Python program to use the same global variable in two different functions and modify its value.
Q10. Write a Python program to create a counter using a nested function that updates a nonlocal
variable.
Q1: What is scope in Python?
Q2: Where is a variable declared inside a function visible?
Q3: What is the default scope of a variable defined outside any function?
Q4: What does the global keyword do?
Q5: What will happen if you try to modify a global variable without global keyword?
Q6: What is the purpose of nonlocal keyword?
Q7: What is LEGB rule?
Q8: Which is the outermost scope in Python?
Q9: Which scope comes just outside a nested function?
Q10: What happens if variable is not found in any scope?