Python / Core Python Fundamentals Interview Questions
What is variable scope in Python and how does the LEGB rule work?
Scope determines where in the code a variable name is visible and accessible. Python resolves names using the LEGB rule, checking four scopes in order: Local → Enclosing → Global → Built-in.
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print(x) # local
inner()
print(x) # enclosing
outer()
print(x) # globalL – Local: names assigned inside the current function.
E – Enclosing: names in any enclosing (outer) function's scope — relevant for nested functions and closures.
G – Global: names assigned at the module's top level.
B – Built-in: names built into Python itself — len, print, range, etc.
To assign to a global variable from inside a function, declare it with global name. To assign to an enclosing-scope variable, use nonlocal name (Python 3+). Without these declarations, Python creates a new local variable instead of modifying the outer one, which is a very common source of bugs in interviews.
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
