def to_string(node):
def actual_recursive(node):
nonlocal a_str # ~global, can modify surrounding function's scope.
a_str += str(node.val)
if node.next != None:
actual_recursive(node.next)
a_str = ''
actual_recursive(node)
return a_str
# nonlocal
# The nonlocal keyword is used to work with variables inside nested functions,
# without 'nonlocal', variable can be accessible but not modified
# with 'nonlocal' declared, you can modify the variable inside nested function
# example with nonlocal keyword
def foo():
def foo2():
nonlocal x
x = "modified"
x = "outer function"
foo2()
return x
print(foo())
#modified
# example without nonlocal keyword
def foo():
def foo2():
x = "cannot be modified without nonlocal declaration"
x = "outer function"
foo2()
return x
print(foo())
#outer function
# combined example + triple nested fxn
# “nonlocal” only works in nested functions
def outer():
def inner():
def innerest():
global x # if declare "nonlocal" here would give an error
x = "innerest function"
print("innerest:", x)
innerest()
global x
x = "outer function"
print("outer:", x)
inner()
x = "global"
print('global:', x)
outer()
# global: global
# outer: outer function
# innerest: innerest function