Junior — Middle
Why is calling a variable that contains a function invalid outside its scope?
sobes.tech AI
Answer from AI
In Python, the scope of a variable determines where it is accessible. If a variable contains a function, it can only be called within the scope where it is defined or where it is accessible through a closure or global scope. Calling it outside the scope of its definition results in a NameError, as the interpreter cannot see this variable.
Example:
def outer():
def inner():
print("Hello")
inner() # correct
outer()
inner() # error, inner is not defined outside outer
Here, inner exists only inside outer, so calling it outside outer is impossible.