Loading

Quipoin Menu

Learn • Practice • Grow

python / Scope and Global
interview

Q1. What are variable scopes in Python?
Python has four scopes: Local (inside a function), Enclosing (in nested functions), Global (module-level), and Built-in (built-in names). LEGB rule (Local, Enclosing, Global, Built-in) determines name resolution. Variables created in a function are local by default.

Q2. How do you modify a global variable inside a function?
Use the global keyword to indicate that a variable refers to the global scope. Example:
count = 0 def increment(): global count count += 1
Without global, Python would create a local variable.

Q3. What is the nonlocal keyword?
nonlocal is used in nested functions to assign to a variable in the enclosing (non-global) scope. It allows modifying variables from outer functions. Example:
def outer(): x = 10 def inner(): nonlocal x x += 1 inner() print(x) # 11

Q4. What is the difference between local and global variables?
Local variables are defined inside a function and are accessible only within that function. Global variables are defined at the module level and are accessible everywhere. Using global variables is generally discouraged as it can make code harder to maintain.

Q5. How do you access a variable from an outer function?
Inner functions can read variables from enclosing scopes without any keyword. For reading, Python will look up through LEGB. To modify, use nonlocal. Example:
def outer(): x = 10 def inner(): print(x) # works, reading inner()