Top Python Quiz Questions 🐍: post #369 — TG.ME

Understanding Python Namespaces: Quick Quiz!

Hey everyone! 👋

Today, I want to share some insights about Python namespaces. A namespace is essentially a container where names are mapped to objects. It helps in organizing the code and avoids naming conflicts.

Here's what you need to know:

- Types of Namespaces:
- Built-in Namespace: Contains names like print() and len().
- Global Namespace: Defined at the top level of a script or module.
- Local Namespace: Created within functions.

- Scope Resolution: Python uses the LEGB rule to locate variables:
- Local: Inside the current function.
- Enclosing: In the local scope of enclosing functions.
- Global: At the module level.
- Built-in: Names pre-defined in Python.

Here's a quick example:

x = 'global'

def outer():
x = 'enclosing'

def inner():
x = 'local'
print(x) # Prints 'local'

inner()
print(x) # Prints 'enclosing'

outer()
print(x) # Prints 'global'


Namespaces are crucial for clean and effective coding. Keep practicing and exploring! 💻
April 14, 2025 558