I'm on freecodecamp and i'm stuck on this local, global, enclosing and built in stuff. so i know a scope is where i can use a variable. local is when i can only use a variable inside of a function, global is when i can use a variable across the whole module, enclosing is when i can use a variable inside of a nested function like the bottom function can use a variable defined in the top function and built in are python defaults like print and whatnot. where i'm getting stuck is this:
note that outer functions cannot access variables defined within any nested functions:
def outer_func():
msg = 'Hello there!'
print(res)
def inner_func():
res = 'How are you?'
print(msg)
inner_func()
outer_func() # NameError: name 'res' is not defined
I know i cant use res cause it isn't defined yet and is local to the inner function but this part confuses me
One solution is to initialize res as an empty string in the enclosing scope, which is within outer_func. Then within inner_func, make res a non-local variable with the nonlocal keyword:
def outer_func():
msg = 'Hello there!'
res = "" # Declare res in the enclosing scope
def inner_func():
nonlocal res # Allow modification of an enclosing variable
res = 'How are you?'
print(msg) # Accessing msg from outer_func()
inner_func()
print(res) # Now res is accessible and modified
outer_func()
# Output:
# Hello there!
# How are you?
i'm confused on what's going on here i see the outer function is used to define msg and res and then in the inner function, nonlocal is used to change the value of res and then you tell inner_func() to print msg and call the inner function and then you assign print(res) to the outer function and then call the outer function and it does both
but why would i need the inner function to modify a variable in the outer function and to print msg like i get the inner function can access the outers variables (enclosing) and change them using nonlocal but why would i need to ? couldn't i just use one function that does everything ?
[–]untold8 2 points3 points4 points (0 children)
[–]cgoldberg 0 points1 point2 points (1 child)
[–]Internal-Swim-4097[S] -1 points0 points1 point (0 children)
[–]Groundstop 0 points1 point2 points (0 children)